Python开发Discord机器人 调用cleverbotfree实现chatbot频道自动回复求助
问题排查与修复说明
- 核心错误:异步事件
on_message中调用同步函数并执行asyncio.run(),和discord.py本身运行的事件循环冲突,导致异步调用失败。直接删除冗余的同步send函数,在chatbot分支直接await调用async_chat即可。 - 缺失命令处理逻辑:重写
on_message事件后没有添加await client.process_commands(message),会导致所有自定义!前缀命令失效。 - 语法错误:
workingon命令中ctx.send前缺失await,request命令中成员提及属性拼写错误(metion改为mention)。 - 逻辑优化:添加机器人自身消息过滤,避免在chatbot频道自己和自己循环对话。
修复后完整代码
import discord from webserver import keep_alive import os from discord.ext import commands import asyncio from cleverbotfree import CleverbotAsync requests = [] client = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @client.command() async def request(ctx, request: str,member: discord.Member): requests.append('{0}: {1}'.format(member,request)) await ctx.send(f'Thanks {member.mention} for the request, my dev will (hopefully) get right to work!') @client.command(description="See what my dev is working on") async def workingon(ctx): await ctx.send("My Dev is currently working on adding a feature in where, in a channel called 'chatbot', it will respond like a human.(though he has spent hours on it, it still doesn't work)") @client.event async def on_ready(): #confirming login print('Logged on as {0.user}'.format(client)) @client.event async def on_member_join(member): print(f'Greetings {member}, welcome to server') @CleverbotAsync.connect async def async_chat(bot, message, user_input): reply = await bot.single_exchange(user_input) await message.channel.send(f'{reply}') await bot.close() @client.event async def on_message(message): # 过滤机器人自身发送的消息 if message.author == client.user: return #getting variables usrnm = str(message.author).split('#')[0] msg = str(message.content) chnl = str(message.channel.name) if usrnm != str(client.user).split('#')[0] and msg.lower() == 'hello bot': await message.channel.send(f'Hello {usrnm}, how do you do?') if str(msg).split(' ')[0].lower() == 'im': await message.channel.send(f'Hi, {msg}, im a dad!') if msg.lower() == '!newfeatures': await message.channel.send(f'{message.author.mention}, The newest feature added to the bot is that if a new member joins, it will greet them') if msg.lower() == '!help': await message.channel.send(f'{message.author.mention}, Type !help for help. \n\n - Typing "Hello Bot" will make the bot answer\n - typing "im" before anything will make the bot answer\n - Typing !newfeatures will tell you the newest feature added to the bot.') if chnl == 'chatbot': await async_chat(message, msg) # 处理命令 await client.process_commands(message) keep_alive() TOKEN = os.environ.get("DISCORD_BOT_SECRET") client.run(TOKEN)
额外注意
- 运行前确保你在Discord开发者后台给机器人开启了所有必要的Intents权限,尤其是消息内容读取权限,否则机器人无法读取频道消息内容。
- 如果调用cleverbotfree时出现连接超时,属于服务端反爬限制,稍等几分钟再测试即可。
内容的提问来源于stack exchange,提问作者SoumyaCode2021
相关产品推荐
相关产品推荐

