小能豆

如何从特定频道截取消息(discord.py)

py

结果

拦截在 X 频道而不是 Discord 公会内的所有频道中发送的消息。也就是说,它应该只跟踪该频道(由其 ID 标识)中的消息删除,并且只响应!snipe同一频道中的命令。我这里的当前代码会拦截 Discord 公会内发送的每条消息。

问题

我怎样才能拦截 X 频道而不是整个公会发送的消息?

我主要打算在一个公会中运行这个机器人。但是,如果需要的话,它可以扩展到多个公会,那就太好了。

我目前拥有的代码如下。

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

client = commands.Bot(command_prefix="!", self_bot=False)
client.sniped_messages = {}


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


@client.event
async def on_message_delete(message):
    print(f'sniped message {message}')
    client.sniped_messages[message.guild.id] = (
        message.content, message.author, message.channel.name, message.created_at)


@client.command()
async def snipe(ctx):
    try:
        contents, author, channel_name, time = client.sniped_messages[ctx.guild.id]

    except:
        await ctx.channel.send("Couldn't find a message to snipe!")
        return

    embed = discord.Embed(description=contents,
                          color=discord.Color.purple(), timestamp=time)
    embed.set_author(
        name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
    embed.set_footer(text=f"Deleted in : #{channel_name}")

    await ctx.channel.send(embed=embed)

client.run(token, bot=True)

阅读 70

收藏
2025-03-02

共1个答案

小能豆

我将提出两种略有不同的解决方案,因为如果您只在一个公会上运行此机器人,代码可能会更简单。两者的共同点是您需要检查在哪个频道删除了消息,以及在哪个频道!snipe发送了命令。

单公会版本

如果您只监控/狙击一个公会的一个频道,那么您只能跟踪一条已删除的消息。因此,您不需要像您发布的代码中那样使用字典;您可以只保留一条消息或None

您已经从单独的文件导入了令牌,因此,为了方便起见,您不妨将频道 ID(与int机器人令牌不同,它是一个 )也放在那里。请注意,按照惯例,常量(您不打算更改的变量)在 Python 中通常全部大写。tokens.py看起来像这样:

TOKEN = 'string of characters here'
CHANNEL_ID = 123456789 # actually a 17- or 18-digit integer

机器人本身:

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_delete(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'sniped message: {message}')
        client.sniped_message = message

@client.command()
async def snipe(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 snipe!")
        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"Deleted in: #{message.channel.name}")

    await ctx.channel.send(embed=embed)

client.run(TOKEN)

多公会版本

如果您在多个公会中分别监控一个频道,则需要分别跟踪它们。方便的是,频道 ID 是全局唯一的,而不仅仅是在单个公会内。因此,您可以仅通过 ID 来跟踪它们,而不必同时包含公会 ID。

您可以将它们保存在列表中,但我建议使用集合,因为检查某个东西是否在集合中更快。注释可以帮助您记住哪个是哪个,这可能也是一个好主意。

TOKEN = 'string of characters here'
# Not a dictionary, even though it uses {}
CHANNEL_IDS = {
    # That one guild
    123456789,
    # The other guild
    987654322,
}

然后,您不再检查单个频道 ID,而是检查它是否多个 ID 的集合中。

import discord
from discord.ext import commands
from tokens import TOKEN, CHANNEL_IDS

client = commands.Bot(command_prefix='!')
client.sniped_messages = {}

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

@client.event
async def on_message_delete(message):
    # Make sure it's in a watched channel, and not one of the bot's own
    # messages.
    if message.channel.id in CHANNEL_IDS and message.author != client.user:
        print(f'sniped message: {message}')
        client.sniped_messages[message.channel.id] = message

@client.command()
async def snipe(ctx):
    # Only respond to the command in a watched channel.
    if ctx.channel.id not in CHANNEL_IDS:
        return

    try:
        message = client.sniped_messages[ctx.channel.id]
    # See note below
    except KeyError:
        await ctx.channel.send("Couldn't find a message to snipe!")
        return

    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"Deleted in: #{message.channel.name}")

    await ctx.channel.send(embed=embed)

client.run(TOKEN)

注意:像原始代码中那样使用裸except子句通常不是一个好主意。这里我们只想捕获KeyError,如果请求的键不在字典中,则会引发该子句。

您可以选择以不同的方式实现相同的逻辑:

message = client.sniped_messages.get(ctx.channel.id)
if message is None:
    await ctx.channel.send("Couldn't find a message to snipe!")
    return

字典的.get()方法会像普通索引一样返回相应的项。但是,如果没有这样的键,它不会引发异常,而是返回默认值(即None如果您在调用时未指定默认值get)。

如果您使用的是 Python 3.8+,则前两行也可以使用赋值表达式(使用“海象运算符”)组合,该赋值表达式可以同时分配和检查:

if (message := client.sniped_messages.get(ctx.channel.id)) is None:
    await ctx.channel.send("Couldn't find a message to snipe!")
    return

提到这些替代方案是为了完整性;所有这些做法都很好。

2025-03-02