阅读电报群组消息

时间:2018-12-14 22:35:50

标签: python telegram telegram-bot

我属于一个电报组。我想在我的python代码中读取这些消息。有什么方法可以读取这些消息而无需在该组中添加漫游器。例如,abc是我的用户ID ...并且abc已添加到xyz组中。因此想在我的python代码中读取xyz组消息。

2 个答案:

答案 0 :(得分:3)

是的,您可以使用名为Telethon的Telegram API来实现。

Telethon Github

这里是设置Telethon API流程的示例。我已编写此代码,以从一个电报组中提取所有新发布的图像。它将使您了解如何开始使用它。

import sys
import os

from telethon import TelegramClient
from telethon.tl.functions.messages import GetFullChatRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.functions.channels import GetChannelsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
import re
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 11111  #number
api_hash = 'x'#string
phone = 'x'
client = TelegramClient('session_name', api_id, api_hash,update_workers=1, spawn_read_thread=False)
client.connect()

如果您对此Telethon集成的所有代码都感兴趣,则可以在以下GitHub链接中找到它;

Telegram Group Bot

答案 1 :(得分:0)

基于此线程:thread

我发现这段代码真的很适合我。请注意,这是一个同步功能,如果您想同时使用多个频道,您可能需要使用 asyncio。下一个链接中的详细信息 --> Async Quick-Start

from telethon import TelegramClient, events, sync

api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)

@client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
    print(event.raw_text)

client.start()
client.run_until_disconnected()

对于上面的代码,您必须将“channel_name”替换为您的用户所在的组的名称。 api_id 和 api_hash 是在 Telegram 中设置 API 应用程序时获取的。