提问人:Turkey Once said 提问时间:6/27/2023 最后编辑:InSyncTurkey Once said 更新时间:6/28/2023 访问量:41
通过 discord 机器人对输入词进行维基百科解释
Giving the wikipedia explanation of the input word via discord bot
问:
import discord
import wikipedia
client = discord.Client()
channel = client.get_channel(#channel id)
@client.event
async def on_ready():
print("Ready")
@client.event
async def on_message(message):
while True:
try:
if str(message.channel) == "genel" and message.content != "" and message.content.startswith('!info'):
parts = message.content.split()
user_choice = str(parts[1:])
user_choice.split()
await message.channel.send(wikipedia.summary(user_choice, sentences=3))
print("Succesful")
except wikipedia.PageError:
print("Wrong")
await message.channel.send("You word is not on the list try another one.")
client.run("#client token")
没有任何问题。当我运行代码时,没有显示任何错误,我的机器人联机。Evendough 每个人的想法似乎都还好,它没有给我我想要的东西,什么也没发生。是代码之外的东西还是什么?如果这是我的代码出了什么问题。
谢谢!
答:
0赞
TimG233
6/28/2023
#1
无响应的关键点是,它不仅是通道的名称,而且是属性。因此,if 语句将始终为 false。如果您想检查频道名称,请在您的情况下使用。
您还可以使用代码改进许多方面。message.channel
discord.Textchannel
str(message.channel)
message.channel.name == 'genel'
- 如果只想在 if 语句中检查一个通道,请考虑使用除 name 之外的通道 ID:因为如果其他人使用你的机器人,并且他/她的服务器中也有一个名为“genel”的文本通道,该怎么办?
message.channel.id == your_channel_id
message.content.startswith('!info')
将确保消息内容不为空,因此是多余的。message.content != ''
- 你似乎很困惑。但是你绝对可以简化它,因为你不应该将字符串拆分为列表,将其转换回字符串并再次拆分。并且不分配给任何变量,它应该这样做。
parts = message.content.split(); user_choice = str(parts[1:]); user_choice.split()
user_choice.split()
- 您不需要对事件进行无限期的 while 循环。如果频道中有新消息,则始终会触发该事件。您的无限期 while 循环将使机器人无限次发送相同的答案,并最终受到不和谐的速率限制。(或由包装器限制,甚至维基百科)
on_message
- 请考虑使用机器人而不是客户端,因为机器人支持命令。您不想将所有功能都放入事件中。
on_message
评论
0赞
Turkey Once said
6/29/2023
G233:所以我已经尝试了你的建议,但仍然没有用。但我不认为问题出在你的代码上。我尝试制作一个非常简单的 discord 机器人,当我写“!w”时发送消息,但它没有奏效。我认为这是if message.content.startswith('!w') await message.channel.send()代码很好,因为ı尝试通过向终端写入消息来发送消息,并且工作正常。
0赞
TimG233
6/29/2023
@TurkeyOncesaid 似乎你错过了意图。如果您的机器人由您自己的机器人使用(少于 100 台服务器),则可以使用它并将其传递到客户端,例如 .另外,不要忘记在您的 discord 开发人员门户中打开它们intents = discord.Intents.all()
client = discord.Client(intents=intents)
上一个:Panda 未打印所有表格
评论
user_choice.split()
str(parts[1:])
_, user_choice = message.content.split(maxsplit = 1)
message.content