使用Python进行Telegram机器人开发
创建一个机器人
- 关注机器人 BotFather
- 发送
/newbot
指令给BotFather - 输入昵称
- 输入用户名
- 创建成功,获取到Token并记录
安装必要的库
pip install python-telegram-bot # 安装SDK
pip install -U requests[socks] # 允许支持socks
参考文档
https://docs.python-telegram-bot.org/
编写最简单的机器人程序
# 以下代码为接受用户输入的 /start 事件
from telegram.ext import Updater, CommandHandler
token = "54295**********************_gZwYs5p-u4"
# 初始化Bot,由于某些原因,国内需要增加proxy代理
# Updater更新者可以按照给定的TOKEN取得Telegram上的所有事件
updater = Updater(token=token, use_context=False, request_kwargs={'proxy_url': 'socks5h://127.0.0.1:7890/'})
# 构建一个调度器
# 处理用户输入的指令,例如 /start
dispatch = updater.dispatcher
# 添加指令方法
def start(bot, update):
print(bot) # 机器人信息,包含机器人ID,用户名,昵称
print(update) # 负责处理本次通讯的请求和响应
message = update.message
chat = message['chat']
update.message.reply_text(text="Hello world") # 返回普通文本
# 注册指令到调度器
dispatch.add_handler(CommandHandler('start', start))
if __name__ == '__main__':
updater.start_polling() # 启动Bot
运行Bot
# 运行
updater.start_polling()
# 退出
updater.stop()
Telegram Bot 开发的代理设置
# Updater
updater = Updater(token=TOKEN, request_kwargs={'proxy_url': 'socks5h://127.0.0.1:1080/'})
#Bot
proxy = telegram.utils.request.Request(proxy_url='socks5h://127.0.0.1:1080')
bot = telegram.Bot(token=TOKEN, request=proxy)
# 直接使用proxychains4运行程序
proxychains4 python main.py
给指定对象发送消息
def send(bot, update):
who = "5356279000"
msg = "你好"
dispatch.bot.sendMessage(chat_id=who, text=msg)
dispatch.add_handler(CommandHandler('send', send))
非指令消息事件接收
from telegram.ext import Updater, MessageHandler, Filters
def echo(bot, update):
text = update.message.text
update.message.reply_text(text=text)
# 过滤器:Filters.text 当接收到的消息为文本时,触发echo函数
# 除此之外,还有以下几种类型
# audio,sticker,video,sticker
dispatch.add_handler(MessageHandler(Filters.text, echo))
返回按钮列表
from telegram import InlineKeyboardMarkup,InlineKeyboardButton
def menu(bot,update):
update.message.reply_text("随便给点东西",reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton("按钮1","链接1"),
InlineKeyboardButton("按钮3","链接2")
], # 一行两个
[InlineKeyboardButton("按钮2","链接3")],# 一行一个
]))
dispatch.add_handler(CommandHandler('menu', menu))
返回可点击的选项
from telegram import InlineKeyboardMarkup,InlineKeyboardButton
from telegram.ext import CallbackQueryHandler
def check(bot, update):
update.message.reply_text("随便给点东西", reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("选项1", callback_data="opt1")],
[InlineKeyboardButton("选项2", callback_data="opt2")],
]))
def option(bot, update):
data = update.callback_query.data
print(data)
dispatch.add_handler(CommandHandler('check', check))
dispatch.add_handler(CallbackQueryHandler(option))
返回图片
def image(bot, update):
update.message.reply_sticker("图片地址")
dispatch.add_handler(CommandHandler('image', image))