【问题标题】:Having trouble with discord.py bot repeating itself with on_message() and modifying user messagesdiscord.py bot 使用 on_message() 重复并修改用户消息时遇到问题
【发布时间】:2018-05-01 21:20:18
【问题描述】:

我正在尝试使用 on_message() 命令让机器人识别特定类型的消息,并返回该消息的修改版本;这是一个例子:

import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import platform
import logging

logging.basicConfig(level=logging.INFO)

client = Bot(description="Basic Bot by Habchy#1665", command_prefix="!",     pm_help = True)

@client.command()
async def ping(*args):

    await client.say(":ping_pong: Pong!")
    await asyncio.sleep(3)

@client.event
async def on_message(message):

    if message.content.startswith('ABDD'):

        newMessage = message.content[:]

        newMessage.replace("D","C",1)

        await client.send_message(message.channel, "Fixed!")
        await client.send_message(message.channel, newMessage)

    await client.process_commands(message)


client.run('my auth code')

我遇到的第一个问题是我的机器人重复消息“已修复!”和“ABDD”不断,直到我关闭它。

我遇到的第二个问题是它似乎没有将“ABDD”更改为“ABCD”

我对整个机器人制作这件事还很陌生,我希望能在这个问题上得到一些帮助。谢谢!

我正在使用 Habchy 的 BasicBot 作为我的机器人的框架。

【问题讨论】:

    标签: python python-3.6 discord discord.py


    【解决方案1】:

    我无法告诉您是什么导致了重复消息,但它不会将 ABDD 更改为 ABCD 的原因是因为 str.replace() 返回一个新字符串而不是编辑旧字符串。

    newMessage.replace("D","C",1) 更改为newMessage = newMessage.replace("D","C",1)

    【讨论】:

    • 这奇怪地解决了这两个问题,我忘记了字符串是不可变的。谢谢!
    • 再想一想之后,它一遍又一遍地发送的原因是因为您没有检查以确保您没有回复自己。 if message.author.id == bot.user.id: return
    猜你喜欢
    • 2022-07-09
    • 1970-01-01
    • 2021-12-04
    • 2020-11-07
    • 2012-12-12
    • 2020-10-26
    • 2020-11-17
    • 2020-09-16
    • 2021-10-18
    相关资源
    最近更新 更多