首页 > 编程问答 >使用 telethon 从公共电报频道读取消息

使用 telethon 从公共电报频道读取消息

时间:2024-07-28 06:14:41浏览次数:11  
标签:python telegram telethon

我正在使用 Telethon 来自动化 Telegram 频道中的一些内容。我已经获得了 API 密钥、哈希值和令牌,并且可以使用 Telethon 启动新会话。

问题是,当新消息从某些选定通道到达时,我想打印文本,但打印我编写的代码似乎不起作用,我不明白为什么。 它正确进入打印“Listening”的循环,但当新消息到达时没有打印任何内容。

这是我的代码

import configparser
import asyncio

from telethon import TelegramClient, events

# Reading Configs
config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = int(config['Telegram']['api_id'])
api_hash = str(config['Telegram']['api_hash'])
phone = config['Telegram']['phone']
username = config['Telegram']['username']


channels_list = ["channel1", "channel2"] #these are public channel names taken from https://web.telegram.org/k/#@channelname for example



async def main():
    client = TelegramClient('session_name', api_id, api_hash)
    await client.start(phone)

    @client.on(events.newmessage.NewMessage())
    async def my_event_handler(event):
        print("hello")
        print(event)
    sender = await event.get_sender()
        if sender.username in channels_list:
            channel = sender.username
            # get last message of the channel
            async for message in client.iter_messages(channel, limit=1):
                print(message.text)


    print("Listening...")

    await client.run_until_disconnected()




if __name__ == '__main__': 
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

代码中有一些问题导致它无法正常工作。以下是更正后的代码,并附有解释:

import configparser
import asyncio

from telethon import TelegramClient, events
from telethon.tl.types import PeerChannel

# 读取配置
config = configparser.ConfigParser()
config.read("config.ini")

# 设置配置值
api_id = int(config['Telegram']['api_id'])
api_hash = str(config['Telegram']['api_hash'])
phone = config['Telegram']['phone']
username = config['Telegram']['username']

# 使用频道 ID,而不是频道名
channels_list = [-123456789, -987654321]  # 将此替换为实际的频道 ID

async def main():
    client = TelegramClient('session_name', api_id, api_hash)
    await client.start(phone)

    @client.on(events.NewMessage(chats=channels_list))
    async def my_event_handler(event):
        print(f"新消息来自:{event.chat.title}")
        print(f"消息内容:{event.message.text}")

    print("正在监听...")
    await client.run_until_disconnected()

if __name__ == '__main__':
    asyncio.run(main())

代码解释:

  1. 使用频道 ID: 使用频道名来识别频道是不准确的。建议使用频道 ID,因为它是唯一的。你可以通过以下步骤找到频道 ID:
  2. 在 Telegram 应用程序中加入目标频道。
  3. 转到频道信息页面。
  4. 点击频道名称,它会复制频道链接,类似于 https://t.me/channelname
  5. 将链接中的 https://t.me/ 替换为 https://web.telegram.org/z/ 并访问该链接。
  6. 你会在地址栏中看到类似 https://web.telegram.org/z/#-123456789 的内容,其中 -123456789 就是频道 ID。

  7. events.NewMessage(chats=channels_list) : 这个参数告诉 Telethon 只监听指定频道的新消息。

  8. event.chat.title event.message.text : 使用这些属性可以分别获取消息所属的频道名称和消息内容。

  9. 异步代码结构: 使用 asyncio.run(main()) 来运行异步主函数。

其他建议:

  • 确保你的 Telegram 账号已经加入了目标频道。
  • 检查你的 config.ini 文件是否正确配置了 API 密钥、哈希值和电话号码。

通过以上修改,你的代码应该能够正常监听指定频道的新消息并打印相关信息了。

标签:python,telegram,telethon
From: 78799303

相关文章

  • 使用 Python 进行 Web 抓取以获取数据 NoneType ERROR
    我正在努力为我的学校项目获取美元和价格。所以我决定为此使用网络抓取,但我有一个问题。当我尝试在服务器上使用我的代码时,它给我NoneType错误。它可以在googlecolab上使用,但我无法在我的电脑或服务器上使用。我该如何解决这个问题?网页抓取代码;defdolar():he......
  • Python 请求 - response.json() 未按预期工作
    我正在尝试从Python的requests模块调用API。在邮递员上,返回的响应标头中的Content-Type是application/json;charset=utf-8,响应json数据是我期望的样子。但是,在python上的API的get方法之后运行response.json()会抛出错误simplejson.errors......
  • Python 中的“样板”代码?
    Google有一个Python教程,他们将样板代码描述为“不幸的”,并提供了以下示例:#!/usr/bin/python#importmodulesusedhere--sysisaverystandardoneimportsys#Gatherourcodeinamain()functiondefmain():print'Hellothere',sys.argv[1]#Command......
  • Python 3.9.1 中的 collections.abc.Callable 是否有 bug?
    Python3.9包含PEP585并弃用typing模块中的许多类型,转而支持collections.abc中的类型,现在它们支持__class_getitem__例如Callable就是这种情况。对我来说,typing.Callable和collections.abc.Ca......
  • 列表子类的 Python 类型
    我希望能够定义列表子类的内容必须是什么。该类如下所示。classA(list):def__init__(self):list.__init__(self)我想包含键入内容,以便发生以下情况。importtypingclassA(list:typing.List[str]):#Maybesomethinglikethisdef__init__(self):......
  • Python 中类型友好的委托
    考虑以下代码示例defsum(a:int,b:int):returna+bdefwrap(*args,**kwargs):#delegatetosumreturnsum(*args,**kwargs)该代码运行良好,只是类型提示丢失了。在Python中使用*args,**kwargs来实现​​委托模式是很常见的。如果有一种方法可......
  • 使用 python 支持构建自定义 vim 二进制文件
    背景Debian11vim软件包不包含python3支持。请参阅标题为“Debian11vim中不支持python-证据”的部分下面我需要vim支持python3YouCompleteMevim插件为了构建一个新的,我将vim9.0tarball下载到v......
  • 如何在Python 3.12+中正确使用泛型来提高代码质量?
    我正在尝试使用泛型来改进FastAPI应用程序中的类型注释。我有一个抽象存储库类,在其中使用泛型:fromabcimportABC,abstractmethodfromtypingimportListclassAbstractRepository[T](ABC):@abstractmethodasyncdefadd_one(self,data:dict)->T:......
  • python中的while循环不退出
    我试图完成第一年的python商业课程作业,但我的while循环无法退出,有人能帮忙吗?commisionTable=[{"admin_fee":100,"comm_rate":0.10},{"admin_fee":125,"comm_rate":0.12},{"admin_fee":150,"comm_rate":......
  • python---json文件写入
    ​ 使用到的知识点:os模块执行linux指令、json.dump()、withopenasf代码实现importsysimportosimportjson #向json文件file中添加内容data,其中data的类型为字典defwrite_json(file,data):    #如果文件存在,则删除    if(os.path.exists(fi......