【问题标题】:Discord.py auxiliary function not executing textDiscord.py 辅助功能不执行文本
【发布时间】:2019-05-25 04:33:26
【问题描述】:

我有一个使用 Python 运行的 discord 机器人,但是,我正在重写以通过添加一个应减少代码重用的附加函数来压缩代码,以便其他贡献者贡献代码。

但是,在代码中,函数 textCom 无法识别 client.send_message

我尝试将异步添加到 textCom 函数的 def,但是,这导致机器人没有响应。

import discord

TOKEN = 'token'

client = discord.Client()

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    # commands cannot be executed in private messages
    if message.channel.type == discord.ChannelType.private:
        return


    # original code
    if message.content.startswith('!text1'):
        msg = "text1 executed".format(message)
        await client.send_message(message.channel, msg)  

    # new code I want executed
    def textCom(textMessage):
        msg = textMessage.format(message)
        await client.send_message(message.channel, msg)

    if message.content.startswith('!text2'):
        textCom("text2 executed")

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)

但是,当用户键入 !text1 时,机器人会运行 Python 脚本,并回复“已执行 text1”,但当用户键入 !text2 时,机器人不会回复。

【问题讨论】:

    标签: python python-3.x bots discord.py


    【解决方案1】:

    当您定义 on_message 时,解释器应该会在机器人启动之前引发语法错误。在非异步函数中不能有 await

    textCom 设为async def 函数并在调用时将其设为await

    @client.event
    async def on_message(message):
        ...
        async def textCom(textMessage):
            msg = textMessage.format(message)
            await client.send_message(message.channel, msg)
    
        if message.content.startswith('!text2'):
            await textCom("text2 executed")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2019-01-23
      相关资源
      最近更新 更多