【问题标题】:How to send a document with Telegram bot?如何使用 Telegram bot 发送文档?
【发布时间】:2021-12-09 23:33:40
【问题描述】:

我在 youtube 上遵循了一个关于如何创建 Telegram Bot 的教程,现在它只能发送消息,但我什至想发送文件或音频、视频、照片等文件......现在我只是想发送一个文件,但我很困惑,我不知道该怎么做。

机器人的源代码分为 2 个主要文件。一个 responser.py:

def responses(input_text):
    user_message = str(input_text).lower()

    if user_message in ("test", "testing"):
        return "123 working..."
    

    return "The command doesn't exists. Type /help to see the command options."

和 main.py:

import constants as key
from telegram.ext import *
import responser as r

print("Hello. Cleint has just started.")

def start_command(update):
    update.message.reply_text("The Bot Has Started send you command sir.")



def help_command(update):
    update.message.reply_text("""
    Welcome to the Cleint Bot. For this purchase the following commands are available:
    send - send command is to send the log file from the other side of computer""")

def send_document(update, context):
    doc_file = open("image1.png", "rb")
    chat_id = update.effctive_chat.id
    return context.bot.send_document(chat_id, doc_file)

def handle_message(update, context):
    text = str(update.message.text).lower()
    response = r.responses(text)
    update.message.reply_text(response)

def error(update, context):
    print(f"Update {update} cause error: {context.error}")

def main():

    updater = Updater(key.API_KEY, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start_command))
    dp.add_handler(CommandHandler("help", help_command))

    dp.add_handler(MessageHandler(Filters.text, handle_message))
    dp.add_error_handler(error)
    updater.start_polling()
    updater.idle()

main()

有人可以帮帮我吗?

【问题讨论】:

    标签: python python-telegram-bot


    【解决方案1】:

    尝试以下作为您的 send_document 函数:

    def send_document(update, context):
        chat_id = update.message.chat_id
        document = open('image1.png', 'rb')
        context.bot.send_document(chat_id, document)
    

    并在主函数中将命令“发送”添加到机器人,如下所示:

    dp.add_handler(CommandHandler("send", send_document))
    

    这样,如果你在 Telegram 中输入 /send,机器人就会向你发送文档。

    【讨论】:

    • 谢谢!成功了!
    • 随时!祝你好运!
    猜你喜欢
    • 2019-02-16
    • 2018-08-25
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2016-07-09
    相关资源
    最近更新 更多