【问题标题】:Is there any way for a discord bot to send messages as a user who typed a command?有没有办法让不和谐机器人以输入命令的用户身份发送消息?
【发布时间】:2021-03-28 17:18:01
【问题描述】:

我一直在尝试在 python 中创建一个不和谐机器人(使用 discord.py),它可以在用户输入命令时键入消息(在我的例子中是 !spam)。这是我整理的代码。

@client.command()
async def spam(ctx, leng, tim,*,msg):
    import time
    leng = int(leng); tim = int(tim)
    if leng > 10 :
        await ctx.send('Please do not spam too much. The limit is 10 messages.')
    else:
        for i in range(leng) :
            await ctx.send(msg)
            time.sleep(tim)

有谁知道我可以放入的任何代码,可以使机器人以使用该命令的用户的身份键入消息? (所以看起来像是用户输入了消息而不是机器人)。

提前致谢。

【问题讨论】:

    标签: python discord bots discord.py


    【解决方案1】:

    让它看起来像用户发送消息的最佳方法是通过 webhook。它会有他们的头像和名字,但旁边仍然会有 BOT 标签。

    @client.command()
    async def spam(ctx, leng: int, tim: int,*,msg):
        # Checking if a webhook exists already
        webhook = discord.utils.get(await ctx.channel.webhooks(), name='Spammer')
        if webhook is None:
            # If the webhook didn't exist, we create one
            webhook = await ctx.channel.create_webhook(name='Spammer')
        if leng > 10 :
            await ctx.send('Please do not spam too much. The limit is 10 messages.')
        else:
            for i in range(leng) :
                await webhook.send(content=msg, username=ctx.author.display_name, avatar_url=ctx.author.avatar_url)
                await asyncio.sleep(tim)
    

    此外,我继续进行了一些更改,以使您的代码更有效率。首先,我在命令的 def 行中使用了类型提示,当你这样做时,discord.py 将自动转换它们as described here。我还将time.sleep 更改为asyncio.sleep 以避免阻塞as described in the discord.py docs,确保在顶部导入asyncio

    【讨论】:

    • 您好,感谢您帮助我。但是,当我尝试使用 !spam 命令时,会弹出一条错误消息:'method' object is not iterable for the line webhook = discord.utils.get(ctx.chhanel.webhooks, name = 'Spammer')。您知道为什么会发生此错误以及任何解决方法吗?提前致谢。
    • 另外,有什么方法可以从用户身上移除 BOT 标签?提前致谢。
    • 啊,那是我的错,我忘记了 webooks 不是一个属性,而是一个协程(需要等待的异步函数),我已经编辑了我的答案以反映更正。关于您的第二条评论,无法删除 bot 标签 no,这与您能够以用户身份发送消息一样接近。
    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2020-11-19
    • 2020-10-03
    • 2023-04-04
    • 2020-11-12
    • 1970-01-01
    • 2021-10-26
    • 2023-03-08
    相关资源
    最近更新 更多