创建机器人

https://t.me/BotFather 对话:

  1. 输入 /start

  2. 输入 /newbot

  3. 输入 你想创建的机器人名称

  4. 保存BotToken

  5. /setcommands 配置 bot 菜单

命令说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/newbot - create a new bot 新建一个bot
/mybots - edit your bots [beta] 编辑你的bot

Edit Bots
/setname - change a bot's name 更改bot名称
/setdescription - change bot description 更改bot描述
/setabouttext - change bot about info 更改bot info
/setuserpic - change bot profile photo 更改bot头像
/setcommands - change the list of commands 设置可用命令
/deletebot - delete a bot 删除bot

Bot Settings
/token - generate authorization token 生成token
/revoke - revoke bot access token 吊销bottoken
/setinline - toggle inline mode (https://core.telegram.org/bots/inline) 使bot支持发送贴纸/地址/视频/图片/文档等
/setinlinegeo - toggle inline location requests (https://core.telegram.org/bots/inline#location-based-results) 使机器人拥有访问用户位置的权限
/setinlinefeedback - change inline feedback (https://core.telegram.org/bots/inline#collecting-feedback) settings 收集inline bot的使用统计
/setjoingroups - can your bot be added to groups? 设置bot能否加入群组
/setprivacy - toggle privacy mode (https://core.telegram.org/bots#privacy-mode) in groups 设置bot在群组内的隐私模式(别人无法看见其他人发的/内容)

Games (现阶段仅支持h5游戏,flash不会支持)
/mygames - edit your games (https://core.telegram.org/bots/games) [beta] 编辑游戏
/newgame - create a new game (https://core.telegram.org/bots/games) 创建新游戏
/listgames - get a list of your games 列出你的所有游戏名称
/editgame - edit a game 编辑游戏
/deletegame - delete an existing game 删除现有游戏

安装依赖

1
pip install python-telegram-bot --upgrade

一些api

Python-telegram-bot是一个强大的Python库,用于创建和管理Telegram机器人。下面是一些与该库相关的重要API和概念的简要介绍:

  1. telegram 模块telegram模块包含了所有与Telegram Bot API交互的类和方法。这些类包括UpdateMessageUserBot等,用于处理消息、用户和机器人等。
  2. Updater Updater是python-telegram-bot库的核心组件,用于处理与Telegram服务器之间的通信和更新。您可以使用Updater初始化机器人,设置Webhook,处理更新等。
  3. CommandHandlerCommandHandler是一个处理命令的处理程序,允许您定义机器人如何响应用户发送的命令。例如,您可以使用来处理 /start/help等命令。
  4. CallbackQueryHandlerCallbackQueryHandler是一个处理内联键盘按钮单击的处理程序。用于响应用户通过内联键盘发送的回调查询,使机器人能够根据按钮点击执行相应的操作。
  5. InlineKeyboardButton InlineKeyboardMarkup:这些类用于创建内联键盘按钮和键盘标记。InlineKeyboardButton用于定义按钮的文本和回调数据,而InlineKeyboardMarkup用于将按钮组成键盘并将其发送给用户。
  6. Update Update表示从Telegram服务器接收的更新,包括用户消息、回调查询和其他与机器人互动相关的信息。
  7. Message Message表示Telegram上的消息。您可以使用来访问消息的文本、发送者、聊天等信息。
  8. User User表示Telegram用户。您可以使用来访问用户的ID、用户名、名称等信息。
  9. Bot Bot是机器人的主要接口。通过创建Bot实例,您可以向Telegram服务器发送消息、查询用户信息、设置Webhook等。
  10. ReplyKeyboardMarkup ReplyKeyboardRemove:这些类用于创建回复键盘,允许用户从固定选项中进行选择。ReplyKeyboardRemove用于删除回复键盘。
  11. Webhook和轮询:您可以选择使用Webhook或轮询来获取更新。Webhook是一种被动方式,您将机器人的URL绑定到Telegram服务器,并在有新更新时接收们。轮询是主动方式,机器人定期向Telegram服务器发出请求以获取更新

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from telegram import Update   # 获取消息队列的
from telegram.ext import filters, ContextTypes, MessageHandler, ApplicationBuilder, CommandHandler

# 回复固定内容
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# 定义一些行为
pass
# 向发来 /start 的用户发送消息,chat_id 后跟用户的 chat_id,text 就是发送的内容
await context.bot.send_message(chat_id=update.effective_chat.id,
text=f"这是一个转存机器人")

# 返回 ID
async def myid(update: Update, context: ContextTypes.DEFAULT_TYPE):
# update.effective_chat.id 就是向机器人发消息的那个用户的 chat id
your_chat_id = update.effective_chat.id
await context.bot.send_message(chat_id=your_chat_id, text=f'你的 chat id 是 {your_chat_id}')

if __name__ == '__main__':
# 创建机器人实例的
bot_token =
proxy = 'http://127.0.0.1:7890'
application = ApplicationBuilder().token(bot_token).proxy(proxy).get_updates_proxy(proxy).build()

# 接收到 /start 执行哪个函数,左边是指令,右边是定义动作的函数
application.add_handler(CommandHandler('start', start))
# 返回用户 chat id 的
application.add_handler(CommandHandler('myid', myid))
# (~filters.COMMAND) filters 是过滤,~ 是取反,就是所有非指令的消息
application.add_handler(MessageHandler((~filters.COMMAND), other_command))

# 启动,直到按 Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler

async def start(update: Update, context: CallbackContext):
# 创建一个具有两个按钮的内联键盘
keyboard = [
[InlineKeyboardButton("选项 1", callback_data='1'),
InlineKeyboardButton("选项 2", callback_data='2')],
]

reply_markup = InlineKeyboardMarkup(keyboard)

# 发送带有键盘的消息
await update.message.reply_text('请选择:', reply_markup=reply_markup)

async def button(update: Update, context: CallbackContext):
query = update.callback_query

# 确认按钮单击
await query.answer()

# 处理回调数据
if query.data == '1':
await query.edit_message_text(text="您点击了选项 1!")
elif query.data == '2':
await query.edit_message_text(text="您点击了选项 2!")

def main():
# 初始化Telegram Updater
updater = Updater(token='您的机器人令牌', use_context=True)
dp = updater.dispatcher

# 为'/start'命令和按钮单击添加处理程序
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CallbackQueryHandler(button))

# 开始轮询更新
updater.start_polling()
updater.idle()

if __name__ == '__main__':
main()