HTML游戏集成Telegram Bot实现玩家分数展示求助
解决方案:Telegram HTML游戏集成用户信息与高分展示
一、捕获Telegram用户名
当用户从Telegram打开你的HTML游戏时,Telegram会自动在游戏页面的URL中附加user参数(JSON格式),包含用户ID、用户名等核心信息。你可以通过JavaScript直接解析该参数:
// 解析URL中的Telegram用户信息 function getTelegramUser() { const urlParams = new URLSearchParams(window.location.search); const userParam = urlParams.get('user'); if (userParam) { try { return JSON.parse(decodeURIComponent(userParam)); } catch (e) { console.error('解析用户信息失败:', e); return null; } } return null; } // 使用示例:获取当前玩家用户名 const telegramUser = getTelegramUser(); if (telegramUser) { const playerName = telegramUser.username || telegramUser.first_name; console.log('当前玩家:', playerName); // 可将用户ID和用户名存储,用于后续分数提交 }
二、后端Python Bot集成分数接口
你需要通过Python Bot后端完成分数存储与高分查询,核心是调用Telegram的setGameScore和getGameHighScores接口,以下是优化后的可运行代码:
import asyncio from telegram import Bot from flask import Flask, request, jsonify # 替换为你的Bot Token BOT_TOKEN = '你的Bot Token' bot = Bot(token=BOT_TOKEN) app = Flask(__name__) # 存储玩家分数(必须先调用此接口,getGameHighScores才能获取数据) async def set_player_score(user_id, score, chat_id=None, message_id=None): try: await bot.set_game_score( user_id=user_id, score=score, chat_id=chat_id, message_id=message_id, force=True # 强制更新更高分数 ) return True except Exception as e: print(f"存储分数失败: {e}") return False # 获取游戏高分列表 async def get_high_scores(user_id, chat_id=None, message_id=None): try: high_scores = await bot.get_game_high_scores( user_id=user_id, chat_id=chat_id, message_id=message_id ) # 整理为前端易处理的格式 formatted_scores = [] for entry in high_scores: user = entry.user formatted_scores.append({ 'username': user.username or user.first_name, 'score': entry.score }) return formatted_scores except Exception as e: print(f"获取高分失败: {e}") return [] # 供前端调用的分数提交接口 @app.route('/submit-score', methods=['POST']) def submit_score(): data = request.json user_id = data.get('user_id') score = data.get('score') chat_id = data.get('chat_id') message_id = data.get('message_id') success = asyncio.run(set_player_score(user_id, score, chat_id, message_id)) return jsonify({'success': success}) # 供前端调用的高分查询接口 @app.route('/get-high-scores', methods=['POST']) def get_high_scores_route(): data = request.json user_id = data.get('user_id') chat_id = data.get('chat_id') message_id = data.get('message_id') scores = asyncio.run(get_high_scores(user_id, chat_id, message_id)) return jsonify({'scores': scores}) if __name__ == '__main__': # 部署到公网时需配置合适的端口和域名 app.run(host='0.0.0.0', port=5000)
三、HTML游戏与后端交互展示高分
在游戏结束后,通过JavaScript调用后端接口提交分数并拉取高分列表展示:
// 提交分数到后端 async function submitScore(score, user_id, chat_id, message_id) { try { const response = await fetch('http://你的后端公网地址/submit-score', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ user_id: user_id, score: score, chat_id: chat_id, message_id: message_id }) }); return (await response.json()).success; } catch (e) { console.error('提交分数失败:', e); return false; } } // 加载并展示高分列表 async function loadHighScores(user_id, chat_id, message_id) { try { const response = await fetch('http://你的后端公网地址/get-high-scores', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ user_id: user_id, chat_id: chat_id, message_id: message_id }) }); const result = await response.json(); const scoresContainer = document.getElementById('high-scores'); scoresContainer.innerHTML = '<h3>游戏高分榜</h3>'; result.scores.forEach((item, index) => { const scoreItem = document.createElement('div'); scoreItem.textContent = `${index+1}. ${item.username}: ${item.score}`; scoresContainer.appendChild(scoreItem); }); } catch (e) { console.error('加载高分失败:', e); } } // 游戏结束触发逻辑 function onGameOver(finalScore) { const user = getTelegramUser(); if (!user) return; // 从URL获取聊天ID和消息ID(Telegram自动附加) const urlParams = new URLSearchParams(window.location.search); const chatParam = urlParams.get('chat'); const chatId = chatParam ? JSON.parse(decodeURIComponent(chatParam)).id : null; const messageId = urlParams.get('message_id'); // 提交分数后加载高分榜 submitScore(finalScore, user.id, chatId, messageId).then(() => { loadHighScores(user.id, chatId, messageId); }); }
四、关键注意事项
- URL参数获取:除
user外,Telegram还会附加chat(聊天ID)和message_id(游戏消息ID),这两个参数是调用Telegram游戏接口的必需参数 - 后端部署:Python后端必须部署到公网可访问的服务器,否则HTML游戏无法调用接口
- Bot配置:确保在BotFather中为你的Bot开启游戏权限,并正确关联游戏
- 跨域处理:后端需配置CORS规则,允许Telegram域名访问接口
内容的提问来源于stack exchange,提问作者TCREV Rev
相关产品推荐
相关产品推荐

