【问题标题】:How to set a welcome channel discord.py?如何设置欢迎频道 discord.py?
【发布时间】:2021-02-21 21:15:06
【问题描述】:

我正在制作一个带有欢迎信息的公共审核机器人,但我怎样才能让人们设置他们的欢迎频道? 我有这个,但这不起作用,它说它设置了频道,但如果有人加入,则没有实际消息。有人可以帮我弄这个吗?这是我的代码:

async def on_member_join(member):
    global welcome_channel_dict
    channel_id = welcome_channel_dict[member.guild.id]
    await client.get_channel(channel_id).send(f'{member.mention} welcome to the Otay! Support server! Enjoy your stay!????')

@client.command(name='welcome')
async def set_welcome_channel(ctx, channel: discord.TextChannel):
    global welcome_channel_dict
    welcome_channel_dict[ctx.guild.id] = channel.id
    await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')```

【问题讨论】:

  • 您收到 on_member_join 事件了吗?我想你必须enable the Server Members Intent in the developer portal
  • 我这样做了,但还是不行
  • 我刚刚用我的机器人测试了你的代码,它工作得很好。如果这是您的确切代码,请确保在 on_member_join 上添加 @client.event
  • 糟糕,我忘了复制顶部的@client.event。但这对我仍然不起作用
  • 我不确定我是否遵循。你遇到了什么错误?您必须先定义welcome_channel_dict,然后您的命令才能查找全局变量。此外,如果您在代码本身中定义字典,然后添加信息,它会在您每次重新启动机器人时删除所有信息。因此,请尝试将信息存储在单独的 JSON 文件中,然后改为查找/添加信息

标签: discord.py


【解决方案1】:

您说您在开发人员门户中启用了意图,您还记得在机器人代码中定义意图吗?你需要设置:

import json

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix = 'your_prefix', intents = intents)

Cloud 为 JSON 提供了一个非常好的教程。你可以在你的代码中做这样的事情,这样当你的机器人重置时,dict就不会重置。

在您的根目录中创建一个“guilds.json”文件。打开该字典并简单地添加{},你就可以开始了。

@client.event
async def on_member_join(member):
    with open('guilds.json', 'r', encoding='utf-8') as f:
        guilds_dict = json.load(f)

    channel_id = guilds_dict[str(member.guild.id)]
    await client.get_channel(int(channel_id)).send(f'{member.mention} welcome to the Otay! Support server! Enjoy your stay!?')


@client.command(name='welcome')
async def set_welcome_channel(ctx, channel: discord.TextChannel):
    with open('guilds.json', 'r', encoding='utf-8') as f:
        guilds_dict = json.load(f)

    guilds_dict[str(ctx.guild.id)] = str(channel.id)
    with open('guilds.json', 'w', encoding='utf-8') as f:
        json.dump(guilds_dict, f, indent=4, ensure_ascii=False)
    
    await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')


# Optional:
# So if your bot leaves a guild, the guild is removed from the dict
@client.event
async def on_guild_remove(guild):
    with open('guilds.json', 'r', encoding='utf-8') as f:
        guilds_dict = json.load(f)

    guilds_dict.pop(guild.id)
    with open('guilds.json', 'w', encoding='utf-8') as f:
        json.dump(guilds_dict, f, indent=4, ensure_ascii=False)

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2021-02-13
    • 2021-08-13
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多