Discord Bots:在另一个命令中检测消息



在我的discord bot (python)上,我试图检测或更确切地说检查命令内发送的消息:如果有人键入命令$start,该命令应该在while循环中检查在$start命令之后发送的消息。如果发送的消息是"join",则发送消息的用户应该被添加到列表中。我试图检测和保存消息在一个变量通过on_message()函数,但它似乎不工作,我不认为我的代码有多大意义,但我不知道如何正确实现它。

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = "$")
@client.event
async def on_ready():
print("started")
sentMsg = ""
users = []
@client.event
async def on_message(msg):
if msg.author == client.user:
return
else:
sentMsg = msg.content
print(sentMsg)
@client.command()
async def start(ctx):
print(sentMsg)
await ctx.send("starting ...")
users.append(ctx.author)
while True:
if sentMsg == "join":
ctx.send("Joined!")
sentMsg = ""
client.run(*token*)

我把sentMsg变量放到了VS-Code的watch部分,它总是显示&;not available&;尽管它打印正确的值。当鼠标悬停在on_message()上时,它会显示:"sentMsg"不能访问Pylance。有人可以改进我的代码,或者有人有更好的想法来实现这一点吗?

我很感激任何人的帮助

不使用on_message事件,您可以使用client.wait_for!

例如:

@client.command()
async def start(ctx):
await ctx.send("starting ...")
try:
message = await client.wait_for('message', timeout=10, check=lambda m: m.author == ctx.author and m.channel == ctx.channel and ctx.content == "join") # You can set the timeout to 'None' 
# if you don't want it to timeout (then you can also remove the 'asyncio.TimeoutError' except case 
# (remember you have to have at least 1 except after a 'try'))
# if you want the bot to cancel this if the message content is not 'join',
# take the last statement from the check and put it here with an if

# what you want to do after "join" message
except asyncio.TimeoutError:
await ctx.send('You failed to respond in time!')
return

相关内容

  • 没有找到相关文章