Home > Software engineering >  Discord.py Fetch Message Bot
Discord.py Fetch Message Bot

Time:07-11

I want to fetch messages from one private discord channel to my channel. But not all messages. Just my wanted ones. Like "car" message. I want to fetch all "car" messages to my discord channel. I don't know programming at all. I'm working on it for 2 days :D. It's so easy I think. But i couldn't do it.

@bot.event
async def on_message(message):
    channel = bot.get_channel(931570478915657790)
    if message.content == "car":
        await channel.send("i found car word!")

I just did this :/

CodePudding user response:

you are using the wrong callback, that callback, '''on_message''' waits until a message is typed to execute. So you kind of have it, but you need to use a different callback.

@bot.command()
async def phrase(ctx, days: int = None):
    if days:
        after_date = dt.datetime.utcnow()-dt.timedelta(days=days)
        # limit can be changed to None but that this would make it a slow operation.
        messages = await ctx.channel.history(limit=10, oldest_first=True, after=after_date).flatten()
        print(messages)
    else:
        await ctx.send("please enter the number of days wanted")

taken from Discord.py: How to go through channel history and count the occurrences of a phrase? ... You then use the messages object to loop over and count the occurrence of desired word

CodePudding user response:

Make sure the channel ID is correct. Also, add an if-statement checking that the message author is not the bot itself. Try this out:

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    channel = bot.get_channel(931570478915657790)
    if "car" in message.content:
        await channel.send("i found car word!")
  • Related