【问题标题】:Bot which interacts with telegram bots与电报机器人交互的机器人
【发布时间】:2020-08-20 03:54:40
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stack Overflow。 SO 不是免费的代码编写服务。向我们展示您尝试解决问题的方法,以及在您的尝试中具体遇到的问题。

标签: python automation bots telegram


【解决方案1】:

telegram 中的机器人之间无法直接交互,因为 Bot API 不支持。 但是您可以使用 MTProto 库来自动化几乎所有与机器人的交互(包括文件下载)。由于这些库只是自动化常规用户帐户,它们没有机器人 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 等运行)并将结果返回给电报机器人。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2022-12-11
    • 2022-01-23
    • 2018-07-22
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多