与电报机器人互动的机器人

时间:2020-05-05 13:10:38

标签: python automation bots telegram

我想知道是否可以自动从其他电报机器人下载文件。我在网上搜索了如何制作可实现此目的的Python机器人(或用Python编写的Telegram机器人),但没有发现任何东西。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

由于Bot API不支持电报中的机器人之间的直接交互,因此无法实现。 但是您可以使用MTProto库自动执行与机器人的几乎所有交互(包括文件下载)。由于这些库仅能自动执行常规用户帐户,因此它们不受bot API的限制。

以下是使用telethon lib下载文件的示例:

from telethon import TelegramClient, events

api_id = <API_ID>
api_hash = '<API_HASH>'
client = TelegramClient('session', api_id, api_hash)

BOT_USER_NAME="@filesending_sample_bot"  # the username of the bot that sends files (images, docs, ...)

@client.on(events.NewMessage(func=lambda e: e.is_private))
async def message_handler(event):
    if event.message.media is not None: # if there's something to download (media)
        await client.download_media(message=event.message, )

async def main():
    await client.send_message(BOT_USER_NAME, 'some text or command to trigger file sending') # trigger the bot here by sending something so that the bot sends the media


client.start()
client.loop.run_until_complete(main())
client.run_until_disconnected()

在我的示例中,我用javascript创建了一个最小的电报机器人,当它收到任何消息以测试上述脚本时会发送照片(作为文档)(但您将上述脚本配置为与您的情况相匹配):

const bot = new (require("telegraf"))(<MY_BOT_TOKEN>);
bot.on("message", (ctx) => ctx.replyWithDocument("https://picsum.photos/200/300"));
bot.launch();

请注意,您必须使用常规电报帐户(而不是使用机器人令牌,而是使用电话号码)进行连接才能正常工作。如果必须使用电报自动程序,则可以在后台使用脚本(通过将其作为新进程或REST api等运行),然后将结果返回给电报自动程序。