错误:使用 python-telegram-bot 在 Telegram Bot 中“不能在‘await’表达式中使用对象字典”

问题描述 投票:0回答:1

嘿嘿!!

我正在使用 python-telegram-bot 框架和 asyncio 来开发 Telegram 机器人以进行异步编程。我的目标是创建一个功能,用户可以单击 Telegram 机器人中的“AI”按钮来提问,然后 ChatGPT 通过我尝试实现的集成来回答这些问题。

这是我处理“AI 会话”中用户的消息的代码部分。当用户发送消息时,我会检查他们是否处于 AI 会话中,如果是,则将消息发送到 ChatGPT 以获得响应。但是,我不断遇到错误“对象字典不能在‘await’表达式中使用”,我不知道为什么。我在这个问题上被困了 5 个小时。

main.py 文件:

from typing import Final
from telegram import Update, KeyboardButton, ReplyKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from gpt_integration import get_gpt_response

TOKEN: Final = 'xxxx'
BOT_USERNAME: Final = '@xxxx'

users_in_ai_session = {}


async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    button_list = [
        [KeyboardButton("/AI"),
         KeyboardButton("/price")]
    ]
    reply_markup = ReplyKeyboardMarkup(
        button_list, resize_keyboard=True, one_time_keyboard=True)
    await update.message.reply_text("Welcome message...", reply_markup=reply_markup)


async def search_price_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Please enter the contract address:")


async def AI_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    users_in_ai_session[user_id] = True
    await update.message.reply_text(
        "You're now chatting with AI. Go ahead, ask me anything!")


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    if users_in_ai_session.get(user_id, False):
        user_input = update.message.text
        # Implement this function based on your GPT model
        response = await get_gpt_response(user_input)
        await update.message.reply_text(response)
    else:
        # Handle non-AI messages
        print("Error")


async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f'Update {update} caused error {context.error}')

if __name__ == '__main__':
    print('Starting bot')
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler('start', start_command))
    # 'AI' is meant to trigger AI interaction
    app.add_handler(CommandHandler('AI', AI_command))
    app.add_handler(CommandHandler('price', search_price_command))
    app.add_handler(MessageHandler(filters.TEXT, handle_message))
    app.add_error_handler(error)
    print('Fetching updates...')
    app.run_polling()

gpt_integration.py 文件:

import httpx


async def get_gpt_response(message_text):
    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://api.openai.com/v1/completions',
            headers={
                'Authorization': 'xxxx'
            },
            json={
                'model': 'gpt-3.5-turbo',
                'prompt': message_text,
                'max_tokens': 50
            },
        )
    data = await response.json()
    return data['choices'][0]['text'].strip()
  1. 确保正确等待所有异步函数。
  2. 检查 get_gpt_response 返回一个可等待的对象。
  3. 查看 Python 的 asyncio 文档以了解可能滥用的等待关键字。 我怀疑这个问题可能与我如何使用await关键字有关,或者可能与如何在异步函数中正确使用字典有关。有人可以帮助我了解导致此错误的原因以及如何修复它吗?
python dictionary async-await openai-api python-telegram-bot
1个回答
0
投票

response.json()
返回一个字典,您不需要
await
。您可以尝试将
data = await response.json()
更改为
data = response.json()

© www.soinside.com 2019 - 2024. All rights reserved.