【问题标题】:Discord Bot w/ Discord.py skipping linesDiscord Bot w/ Discord.py 跳线
【发布时间】:2018-12-02 22:55:46
【问题描述】:

我今天尝试制作一个基于 python discord.py 的机器人以获得一些乐趣,并且遵循一些随机教程并复制代码效果很好,一旦掌握了它,我就添加了一些新命令,但显然大多数命令随机停止工作,由于某种原因,现在只有最底层的命令实际上在不和谐中运行,任何想法为什么会这样? 代码:

import discord
from discord.ext import commands

description = 'Tutorial Bot'
bot_prefix = '!'

client = commands.Bot(description=description, command_prefix=bot_prefix)

list_of_strings = ['hello', 'hi']

@client.event
async def on_ready():
    print('Connected')

@client.event
async def on_message(message):
    if message.content.startswith('!what'):
        await client.send_message(message.channel, 'Huh?')

@client.event
async def on_message(message):
    if message.content in list_of_strings:
        await client.send_message(message.channel, 'Hey there')

client.run('*set to code before attempting*')

我已经将 client.run 设置为最新的代码,但是每当我使用字符串命令的底部列表时它都可以正常工作,但是 !what 部分不起作用。我尝试扭转它们,但同样的问题仍然存在,无论它们处于哪个顺序,只有最底部的一个在工作。我可能在这里遗漏了一些明显的东西吗?

【问题讨论】:

  • 我以前没用过这个,但大概第二个会覆盖第一个...

标签: python bots discord discord.py


【解决方案1】:

我不是 Python 专家,但您的部分问题可能是两个函数声明以相同的方式完全定义。我想第二个函数正在重新定义第一个函数。

@client.event
async def on_message(message):
    //Function 1 code
@client.event
async def on_message(message):
    //Function 2 code

不是使用两个,而是像这样将第二个的条件移动到第一个:

@client.event
async def on_message(message):
    if message.content.startswith('!what'):
        await client.send_message(message.channel, 'Huh?')

    elif message.content in list_of_strings:
        await client.send_message(message.channel, 'Hey there')

【讨论】:

    【解决方案2】:

    当您使用 Client.event 装饰器时,实际上是将 client.on_message 属性分配为您编写的协程。 client.on_message 不能同时是两个东西,所以旧的被丢弃了。

    不过,您的想法是正确的:您应该将命令拆分为离散的单元,而不是将它们保存在一个单一的整体协同程序中。为此,您实际上使用了 Bot.command() 装饰器。

    import discord
    from discord.ext import commands
    
    description = 'Tutorial Bot'
    bot_prefix = '!'
    
    client = commands.Bot(description=description, command_prefix=bot_prefix)
    
    list_of_strings = ['hello', 'hi']
    
    @client.event
    async def on_ready():
        print('Connected')
    
    @client.command(pass_context=True)
    async def what(ctx):
        await client.say('Huh?')
    
    @client.event
    async def on_message(message):
        if message.author == client.user:
            return  # We don't want our bot to respond to itself
        if message.content in list_of_strings:
            await client.send_message(message.channel, 'Hey there')
        await client.process_commands(message)  # Hand off to the command logic
    
    client.run('*set to code before attempting*')
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2020-02-23
      • 2021-04-16
      • 2019-02-26
      • 2018-07-24
      • 2020-08-16
      • 2020-10-18
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多