【问题标题】:Discord Bots: Detecting a message within another commandDiscord Bots:检测另一个命令中的消息
【发布时间】:2021-06-11 00:14:06
【问题描述】:

在我的 discord bot (python) 上,我试图检测或检查命令中发送的消息:如果有人键入命令 $start,则该命令应在 while 循环中检查 $start 之后发送的消息命令。如果发送的消息是“加入”,则发送消息的用户应该被添加到列表中。我试图通过 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 部分,它总是说“不可用”,尽管它打印了正确的值。此外,当在 on_message() 中将鼠标悬停在它上面时,它会说:“sentMsg”未被访问 Pylance。 任何人都可以改进我的代码吗?或者有人有更好的想法来实现它吗?

感谢任何人的帮助

【问题讨论】:

    标签: python discord.py bots message pylance


    【解决方案1】:

    您可以使用 client.wait_for 让机器人检测消息,而不是使用 on_message 事件!

    例如:

    @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
    

    【讨论】:

    • 非常感谢,它成功了!如果有人尝试使用此代码:您必须检查 message.content == "join" (并导入 asyncio)。
    • 如果有效,您可以接受答案,以便其他用户从中受益。
    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2022-08-14
    • 2020-12-20
    • 2020-11-22
    • 2021-11-15
    • 2020-08-17
    相关资源
    最近更新 更多