嘿嘿!!
我正在使用 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()
response.json()
返回一个字典,您不需要 await
。您可以尝试将 data = await response.json()
更改为 data = response.json()
。