【问题标题】:How to fetch messages using discord.py如何使用 discord.py 获取消息
【发布时间】:2024-01-07 20:46:01
【问题描述】:

我创建了一段代码,它曾经是 fetch 函数的 snipe 函数,我假设 snipe 和 fetch 基本上是相反的,我的理论似乎是正确的!但是,事实并非如此,或者我为什么要创建此问题,我在运行 !fetch 命令后遇到消息未获取的问题,没有结果应该是显示内容/消息的嵌入.

关注/问题

运行!fetch 命令后,我的代码没有发送嵌入,控制台/终端中没有列出错误。但是,当在频道内发送消息时,嵌入信息会记录/显示在控制台中(Discord 名称、标签、ID、公会 ID、公会名称等)! 我想从频道获取消息并在运行命令时打印消息。

代码

import discord
from discord.ext import commands
from tokens import token, CHANNEL_ID

client = commands.Bot(command_prefix='!')
client.sniped_message = None

@client.event
async def on_ready():
    print("Your bot is ready.")

@client.event
async def on_message(message):
    # Make sure it's in the watched channel, and not one of the bot's own
    # messages.
    if message.channel.id == CHANNEL_ID and message.author != client.user:
        print(f'Fetched message: {message}')
        client.sniped_message = message

@client.command()
async def fetch(ctx):
    # Only respond to the command in the watched channel.
    if ctx.channel.id != CHANNEL_ID:
        return

    if client.sniped_message is None:
        await ctx.channel.send("Couldn't find a message to fetch!")
        return

    message = client.sniped_message

    embed = discord.Embed(
        description=message.content,
        color=discord.Color.purple(),
        timestamp=message.created_at
    )
    embed.set_author(
        name=f"{message.author.name}#{message.author.discriminator}",
        icon_url=message.author.avatar_url
    )
    embed.set_footer(text=f"Message sent in: #{message.channel.name}")

    await ctx.channel.send(embed=embed)

client.run(token)

我不确定sniped 消息是否对代码有影响。 此外,此代码是从我的朋友那里分享的,他在狙击功能方面得到了帮助。* 谢谢!

【问题讨论】:

    标签: python discord fetch discord.py message


    【解决方案1】:

    来自documentation

    覆盖默认提供的 on_message 会禁止运行任何额外的命令。要解决此问题,请在 on_message 末尾添加 bot.process_commands(message) 行。

    所以你只需要在on_message的末尾添加await client.process_commands(message)

    【讨论】:

    • 欣赏!谢谢。