如何向特定频道发送加入/离开消息

Posted

技术标签:

【中文标题】如何向特定频道发送加入/离开消息【英文标题】:How to send a join/leave message to a specific channel 【发布时间】:2021-12-11 03:07:08 【问题描述】:

最近我一直在为我的服务器开发一个机器人,当用户加入/离开时,我似乎无法让我的机器人在特定频道中发送消息。我一直在研究很多,但我似乎无法让它发挥作用。我已经尝试过async def on_member_join(member):async def on_member_remove(member),但是在加入和离开我的 alt 之后,它似乎甚至没有打印任何内容或给出错误。 (我在 Bot 设置中打开了 Server Members IntentPresence Intent

这是我的部分代码:

client = discord.Client()

# on member join
@client.event
async def on_member_join(member):
    print('member joined')
    channel = client.get_channel(901761695033212939)
    sendmsg = channel.send
    greets = ['greet1', 'greet2', 'greet3', 'greet4', 'greet5', 'greet6']
    n = len(greets) - 1
    num = random.randint(0, n)
    greet = greets[num]
    await sendmsg(f'member ' + greet)

# on member leave
@client.event
async def on_member_remove(member):
    print('member left')
    channel = client.get_channel(901761742609219595)
    sendmsg = channel.send
    byelist = ['bye1', 'bye2', 'bye3']
    n = len(byelist) - 1
    num = random.randint(0, n)
    bye = byelist[num]
    await sendmsg(f'member ' + bye)

【问题讨论】:

如果您还没有这样做,您还需要在代码本身中启用您的意图。 在您的代码中实现intents = discord.Intents.all()。 (在您的client 定义之上)这样做之后,只需说client= discord.Client(intents=intents) 您需要启用bots intesnts 使用intents = discord.Intents.all() 或client/bot = discord.Client/Bot(intents = intents) 【参考方案1】:

既然你已经有了意图,你还需要在你的代码中实现它们。

您可以通过intents = discord.Intents.all() 执行此操作,并且您需要在客户端部分添加intent=intents。那应该可以解决它。

这里是固定的代码:

intents = discord.Intents.all()
client = discord.Client(intents=intents
)

# on member join
@client.event
async def on_member_join(member):
    print('member joined')
    channel = client.get_channel(901761695033212939)
    sendmsg = channel.send
    greets = ['greet1', 'greet2', 'greet3', 'greet4', 'greet5', 'greet6']
    n = len(greets) - 1
    num = random.randint(0, n)
    greet = greets[num]
    await sendmsg(f'member ' + greet)

# on member leave
@client.event
async def on_member_remove(member):
    print('member left')
    channel = client.get_channel(901761742609219595)
    sendmsg = channel.send
    byelist = ['bye1', 'bye2', 'bye3']
    n = len(byelist) - 1
    num = random.randint(0, n)
    bye = byelist[num]
    await sendmsg(f'member ' + bye)

【讨论】:

以上是关于如何向特定频道发送加入/离开消息的主要内容,如果未能解决你的问题,请参考以下文章

如何向特定提及的频道发送消息?

根据参数向特定频道发送消息

Discord.js 在文本频道中加入/离开语音频道通知

如何让机器人在不使用命令的情况下向特定频道中的特定公会发送消息

当有人加入特定频道时发送消息 - Discord Bot

JDA - 向特定频道发送消息