【发布时间】:2023-02-02 23:37:07
【问题描述】:
我的电报机器人有问题,我需要一个 scrypt 来处理来自这个机器人的特定消息并将其发送到电报组,你知道如何帮助我吗? 谢谢
我试过几次,但我得不到好的结果
【问题讨论】:
标签: python telegram telegram-bot sendmessage
我的电报机器人有问题,我需要一个 scrypt 来处理来自这个机器人的特定消息并将其发送到电报组,你知道如何帮助我吗? 谢谢
我试过几次,但我得不到好的结果
【问题讨论】:
标签: python telegram telegram-bot sendmessage
以下是如何使用 python-telegram-bot 库向 Telegram 聊天发送消息的示例:
import logging
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
update_id = None
def main():
"""Run the bot."""
global update_id
# Telegram Bot Authorization Token
bot = telegram.Bot('YOUR_BOT_TOKEN')
# get the first pending update_id, this is so we can skip over it in case
# we get an "Unauthorized" exception.
try:
update_id = bot.get_updates()[0].update_id
except IndexError:
update_id = None
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
while True:
try:
echo(bot)
except NetworkError:
sleep(1)
except Unauthorized:
# The user has removed or blocked the bot.
update_id += 1
def echo(bot):
"""Echo the message the user sent."""
global update_id
# Request updates after the last update_id
for update in bot.get_updates(offset=update_id, timeout=10):
update_id = update.update_id + 1
if update.message: # your bot can receive updates without messages
# Reply to the message
chat_id = update.message.chat_id
message = update.message.text
bot.send_message(chat_id=chat_id, text=message)
if __name__ == '__main__':
main()
将 'YOUR_BOT_TOKEN' 替换为您在创建机器人时从 BotFather 收到的令牌。
此脚本使用 python-telegram-bot 库来处理与 Telegram Bot API 的通信。该脚本首先获取最新的更新 ID 并使用您的机器人令牌创建 telegram.Bot 类的实例。然后,它进入等待更新的循环,并对收到的每条消息发送回复。
【讨论】: