#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. """ import logging import telegram from telegram.error import NetworkError, Unauthorized from time import sleep
update_id = None
defmain(): """Run the bot.""" global update_id # Telegram Bot Authorization Token bot = telegram.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
whileTrue: try: echo(bot) except NetworkError: sleep(1) except Unauthorized: # The user has removed or blocked the bot. update_id += 1
defecho(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 update.message.reply_text(update.message.text)
if __name__ == '__main__': main()
运行
1
proxychains python3 echo.py
使用 Pyrogram
Pyrogram 文档简洁,易用,使用的是 Telegram MTProto API ,性能上更佳,功能上更多,而且可以用不同程序同时运行同一个机器人。
安装
1
pip install --user pyrogram[fast]
例程
将自己之前得到的 api id 和 api hash 在例程中进行相应替换,并替换 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 为自己的 token 。
echo2.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
"""This simple echo bot replies to every private text message. It uses the @on_message decorator to register a MessageHandler and applies two filters on it: Filters.text and Filters.private to make sure it will reply to private text messages only. """