Telegram文本按钮制作方法详解与实操指南
鍦?Telegram 涓垱寤烘枃鏈寜閽紙Inline Keyboard Button锛夊彲浠ラ€氳繃 Telegram Bot API 鎴栫涓夋柟搴擄紙濡?`python-telegram-bot`锛夋潵瀹炵幇銆備互涓嬫槸鍑犵甯歌鐨勬柟娉曪細
1. 浣跨敤 Telegram Bot API锛堝師濮?HTTP 璇锋眰锛?/strong>
閫氳繃 Bot API 鍙戦€佹秷鎭椂锛屽彲浠ュ湪 `reply_markup` 鍙傛暟涓坊鍔?`inline_keyboard` 鏉ュ垱寤烘枃鏈寜閽€?/p>
绀轰緥浠g爜锛圥ython + `requests`锛?/strong>
```python
import requests
TOKEN = "浣犵殑Bot Token
CHAT_ID = "鐩爣鑱婂ぉID
url = f"
瀹氫箟鎸夐挳
keyboard = {
inline_keyboard": [
[{"text": "鎸夐挳1", "callback_data": "button1"}],
[{"text": "鎸夐挳2", "callback_data": "button2"}]
data = {
chat_id": CHAT_ID,
text": "璇烽€夋嫨涓€涓寜閽細",
reply_markup": keyboard
response = requests.post(url, json=data)
print(response.json)
```
鍙傛暟璇存槑
2. 浣跨敤 `python-telegram-bot` 搴擄紙鎺ㄨ崘锛?/strong>
濡傛灉浣犵敤 Python锛屽彲浠ヤ娇鐢?`python-telegram-bot` 搴撴洿绠€鍗曞湴鍒涘缓鎸夐挳銆?/p>
瀹夎搴?/strong>
```bash
pip install python-telegram-bot
```
绀轰緥浠g爜
```python
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
TOKEN = "浣犵殑Bot Token
def start(update, context):
鍒涘缓鎸夐挳
keyboard = [
[InlineKeyboardButton("鎸夐挳1", callback_data="button1")],
[InlineKeyboardButton("鎸夐挳2", callback_data="button2")]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("璇烽€夋嫨涓€涓寜閽細", reply_markup=reply_markup)
def button_click(update, context):
query = update.callback_query
query.answer 闃叉瀹㈡埛绔樉绀衡€滃姞杞戒腑鈥?/p>
query.edit_message_text(f"浣犵偣鍑讳簡: {query.data}")
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(CallbackQueryHandler(button_click))
updater.start_polling
updater.idle
```
浠g爜璇存槑
3. 鍏朵粬璇█瀹炵幇
Node.js锛堜娇鐢?`node-telegram-bot-api`锛?/strong>
```javascript
const TelegramBot = require("node-telegram-bot-api");
const token = "浣犵殑Bot Token";
const bot = new TelegramBot(token, { polling: true });
bot.onText(//start/, (msg) => {
const chatId = msg.chat.id;
const keyboard = {
inline_keyboard: [
[{ text: "鎸夐挳1", callback_
button1" }],
[{ text: "鎸夐挳2", callback_
button2" }]
};
bot.sendMessage(chatId, "璇烽€夋嫨涓€涓寜閽細", { reply_markup: keyboard });
});
bot.on("callback_query", (query) => {
const chatId = query.message.chat.id;
bot.sendMessage(chatId, `浣犵偣鍑讳簡: ${query.data}`);
});
```
4. 鎸夐挳绫诲瀷
闄や簡 `callback_data`锛岃繕鍙互鐢ㄥ叾浠栫被鍨嬬殑鎸夐挳锛?/p>
```python
InlineKeyboardButton("璁块棶鐧惧害", url=")
```
```python
InlineKeyboardButton("鍒嗕韩缁欏叾浠栬亰澶?, switch_inline_query="hello")
```
鎬荤粨
| 鏂规硶 | 閫傜敤鍦烘櫙 | 鎺ㄨ崘搴?|
|||--|
| Bot API锛圚TTP锛?/strong> | 鐩存帴璋冪敤 API锛岄€傚悎浠讳綍璇█ | 猸愨瓙 |
| `python-telegram-bot` | Python 寮€鍙戯紝浠g爜绠€娲?| 猸愨瓙猸?|
| `node-telegram-bot-api` | Node.js 寮€鍙?| 猸愨瓙猸?|
濡傛灉浣犳湁鏇村叿浣撶殑闇€姹傦紙姣斿鎸夐挳鎺掔増銆佸姩鎬佺敓鎴愭寜閽級锛屽彲浠ュ憡璇夋垜锛屾垜浼氭彁渚涙洿璇︾粏鐨勬柟妗堬紒 馃槉
本文章来自(https://www.sdshuangrun.cn),转载请说明出处!
发表评论