telegram 机器人开发(python)
1. 创建一个新的 telegramBot
首先我们需要在tg客户端搜索@BotFather,如下图所示:

创建new bot:选择/newbot

继续操作,为bot取名:

**API token**是非常重要的东西,不要把自己的**API token**泄露给别人!!!如果泄露,别人就有可能控制你的机器人!!!
2. 开发环境准备
IDE:VSCode(请安装必要的python开发插件)
python解释器版本:3.12.3 64-bit
os: windows 11
需要的库:
import asyncio
import logging
from typing import List, Tuple
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import CommandHandler, MessageHandler, filters
from telegram.ext import CallbackContext
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
PicklePersistence,
)
from telegram import Bot
from telegram import InputFile
import pandas as pd
3. 一个简单的示例代码
import asyncio
import logging
from typing import List, Tuple
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import CommandHandler, MessageHandler, filters
from telegram.ext import CallbackContext
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
PicklePersistence,
)
from telegram import Bot
from telegram import InputFile
import pandas as pd
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
def buildkeyboard() -> InlineKeyboardMarkup:
buttons = [
InlineKeyboardButton(text="爬虫", callback_data='1'),
InlineKeyboardButton(text="搜索", callback_data='2'),
InlineKeyboardButton(text="社工", callback_data='3'),
InlineKeyboardButton(text="翻译", callback_data='4'),
InlineKeyboardButton(text="ip", callback_data='5'),
InlineKeyboardButton(text="按钮", callback_data='6'),
InlineKeyboardButton(text="按钮", callback_data='7'),
InlineKeyboardButton(text="按钮", callback_data='8'),
InlineKeyboardButton(text="按钮", callback_data='9')
]
keyboard = [buttons[i:i+3] for i in range(0, len(buttons), 3)]
return InlineKeyboardMarkup(keyboard)
async def start(update: Update, context:ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("请从下面的按钮中选择:", reply_markup=buildkeyboard())
persistence = PicklePersistence(filepath="arbitrarycallbackdatabot")
application = (
Application.builder()
.token("填入你自己的API token")
.persistence(persistence)
.arbitrary_callback_data(True)
.build()
)
# 你需要将 handleuserinput 注册为处理用户输入的消息
application.add_handler(CommandHandler("start", start))
application.run_polling(allowed_updates=Update.ALL_TYPES)
注意:运行代码时你需要同时保持你的tg为在线状态,不要关闭你的tg应用!
运行后,终端输出如下所示:
打开tg,找到@BotFather,点击红线处:

输入指令/start,大功告成!
