0

尝试 sendMessage 时,它​​告诉我未定义聊天 ID。我能够回答CallbackQuery,因为它需要查询 ID 而不是聊天。如果我尝试在回调查询区域的 DEF 中输入“chat_id”,则会引发更多错误

我需要在代码中的哪个位置定义它?

import sys
import time
import os
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton

def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    #creating buttons
    if content_type == 'text':
        if msg['text'] == '/start':
           bot.sendMessage(chat_id, 'Welcome to @UK_Cali Teleshop\n      Created by JonSnow 2021',reply_markup = InlineKeyboardMarkup(inline_keyboard=[
               [InlineKeyboardButton(text="Feedback",callback_data='a'), InlineKeyboardButton(text="You",callback_data='b'),InlineKeyboardButton(text="PGP",callback_data='c'), InlineKeyboardButton(text="Cunt",callback_data='d')],
               [InlineKeyboardButton(text="Products",callback_data='e')]
           ]
       ))
    

def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    print('Callback Query:', query_id, from_id, query_data)


    #find callback data
    if query_data == 'a':
    #bot.sendMessage(chat_id, 'dsuhsdd')
    #answerCallbackQuery puts the message at top
    bot.answerCallbackQuery(query_id, 'products')
        
bot = telepot.Bot('1646167995:AAGsOwfjcryYYkoah69QJ6XGA7koUywmuRk')
MessageLoop(bot, {'chat': on_chat_message,
    'callback_query': on_callback_query}).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)            
4

1 回答 1

1

chat_id变量是本地的on_chat_messageon_callback_query无权访问它。最 Pythonic 的方法会将它们变成一个类并将聊天 ID 存储在成员变量中,但您可以通过添加

    global chat_id

作为 的第一行on_chat_message。您不需要它,on_callback_query因为您没有更改值,尽管它不会受到伤害。

于 2021-03-01T20:26:44.563 回答