【问题标题】:Python Telegram Game Bot function error at 0x7fcfa257f790Python Telegram Game Bot 函数错误在 0x7fcfa257f790
【发布时间】:2021-08-29 07:03:22
【问题描述】:

我是 Python 的新手,最近碰巧设置了一个由 Mark Powers 制作的名为 Telegram Arcade

的机器人(就像你一样......

很明显,它是使用 python-telegram-bot 框架构建的。尽管设置它看起来很简单(附带说明),但我无法让它工作。

即使我更新了一些代码以符合对框架的更改,现在我仍然收到一个错误,该错误与正在与机器人交互的用户一起显示:0x7fcfa257f790 处的函数错误强> .

目前的代码如下:

import configparser, threading, requests, json, re, time, sys

from uuid import uuid4

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram import InlineQueryResultGame, ParseMode, InputTextMessageContent
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, InlineQueryHandler, CommandHandler
from telegram.ext import CallbackContext

from http.server import HTTPServer, BaseHTTPRequestHandler

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


class Global:
    def __init__(self):
        return

class GameHTTPRequestHandler(BaseHTTPRequestHandler):
    def __init__(self, *args):
        BaseHTTPRequestHandler.__init__(self, *args)

    def do_GET(self):
        if "#" in self.path:
            self.path = self.path.split("#")[0]
        if "?" in self.path:
            (route, params) = self.path.split("?")
        else:
            route = self.path
            params = ""
        route = route[1:]
        params = params.split("&")
        if route in Global.games:
            self.send_response(200)
            self.end_headers()
            self.wfile.write(open(route+'.html', 'rb').read())
        elif route == "setScore":
            params = {}
            for item in self.path.split("?")[1].split("&"):
                if "=" in item:
                    pair = item.split("=")
                    params[pair[0]] = pair[1]
            print(params)
            if "imid" in params:
                Global.bot.set_game_score(params["uid"], params["score"], inline_message_id=params["imid"]) 
            else:
                Global.bot.set_game_score(params["uid"], params["score"], message_id=params["mid"], chat_id=params["cid"])
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'Set score')
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'Invalid game!')

def start(update, context):
    bot.send_game(update.message.chat_id, Global.featured)

def error(update, context):
    print(update, error)

def button(update, context):
    print(update)
    query = update.callback_query
    game = query.game_short_name
    uid = str(query.from_user.id)
    if query.message:
        mid = str(query.message.message_id)
        cid = str(query.message.chat.id)
        url = "http://" + Global.host + ":"+Global.port + "/" + game + "?uid="+uid+"&mid="+mid+"&cid="+cid
    else:
        imid = update.callback_query.inline_message_id
        url = "http://" + Global.host + ":"+Global.port + "/" + game + "?uid="+uid+"&imid="+imid
    print(url)
    bot.answer_callback_query(query.id, text=game, url=url)

def inlinequery(update, context):
    query = context.inline_query.query
    results = []
    for game in Global.games:
        if query.lower() in game.lower():
            results.append(InlineQueryResultGame(id=str(uuid4()),game_short_name=game))
    context.inline_query.answer(results)
def main():
    config = configparser.ConfigParser()
    config.read('config.ini')
    token = config['DEFAULT']['API_KEY']
    Global.games = config['DEFAULT']['GAMES'].split(',')
    Global.host = config['DEFAULT']['HOST']
    Global.port = config['DEFAULT']['PORT']
    Global.featured = config['DEFAULT']['FEATURED']
    updater = Updater(token=token, use_context=True)

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(InlineQueryHandler(inlinequery))
    updater.dispatcher.add_handler(CallbackQueryHandler(button))
    updater.dispatcher.add_error_handler(error)
    Global.bot = updater.bot

    print("Polling telegram")
    updater.start_polling()

    print("Starting http server")   
    http = HTTPServer((Global.host, int(Global.port)), GameHTTPRequestHandler)
    http.serve_forever()


if __name__ == '__main__':
    main()

我一直在阅读文档并研究示例,但似乎找不到解决方案。即使 inlineCommands 也无法显示类似的错误。我非常感谢任何建议,很抱歉我不是专家来解释我的情况。谢谢!

【问题讨论】:

  • 这不是错误:它是函数error 的字符串表示。您将 error 传递给其中的 print 调用,因此是消息。
  • @enzo 哦.. 我明白了... nvm 然后... 仍然无法弄清楚为什么它不起作用...
  • 另外:当我尝试在原始 git 中“按原样”运行代码时,我收到以下错误:File "main.py", line 52, in start bot.send_game(update.message.chat_id, Global.featured) AttributeError: 'Update' object has no attribute 'send_game'
  • bot.send_game 更改为Global.bot.send_game 是否有效?
  • 另外,start 函数的签名与original start function 的签名不匹配。当你改变它时它会修复吗?

标签: python bots telegram python-telegram-bot


【解决方案1】:

python-telegram-bot 更改了两年前发布的 v12 中回调的工作方式。您正在使用的 repo 似乎仍然适用于旧的回调。我建议首先尝试让它与 ptb 11.1 版一起使用。或 12.0 没有 传递 use_context=True(在 v12 中,这仍然默认为 False 以实现向后兼容性)。如果效果很好并且您想升级到较新的python-telegram-bot 版本,我强烈建议您阅读v12v13 的转换指南。


免责声明:我目前是python-telegram-bot 的维护者。

【讨论】:

  • 谢谢,我会阅读过渡指南!至于我的问题,似乎有时context. 没有按预期工作。在@enzo 的更正通知之后,我查看了转换指南并进行了相应的升级,但我仍然无法让 inline 工作,直到我恢复到这个:def inlinequery(update, context): query = update.inline_query.query results = [] for game in Global.games: if query.lower() in game.lower(): results.append(InlineQueryResultGame(id=str(uuid4()),game_short_name=game)) update.inline_query.answer(results)
  • 是的,这是有道理的。 update 参数是 Bot API 服务器发送的传入更新 - 在本例中,它包含内联查询。 context 参数包含“仅”与 PTB 设置相关的便利内容。这就是为什么你不能指望context 有一个inline_query 属性;)
猜你喜欢
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2020-06-20
  • 1970-01-01
  • 2021-01-26
  • 2017-11-21
相关资源
最近更新 更多