且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多个服务器的 Discord.py 欢迎消息

更新时间:2023-11-30 12:37:52

如果 bot 规模小得多,比如说只有几台服务器,那么我会说使用 json 文件保存字典不会是一个坏主意.

If the bot is on a much smaller scale, say just a few servers, then I'd say using json file to save a dictionary wouldn't be a bad idea.

您可以在服务器加入服务器时将顶部文本频道的 id 保存为默认值,并让他们更改使用命令的频道,这可以通过 on_guild_join 事件来完成

You can save the id of the top text channel as a default when the server joins the server and let them change what channel to use with commands, this can be done with the on_guild_join event

import json

#sets value in json to guild id upon the bot joining the guild
@client.event
async def on_guild_join(guild):
    #loads json file to dictionary
    with open("filename.json", "r") as f:
        guildInfo = json.load(f)

    guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
    
    #writes dictionary to json file
    with open("filename.json", "w" as f:
        json.dump(guildInfo, f)

#allows server members to set channel for welcome messages to send to    
@client.command()
async def welcomeMessage(ctx):
    with open("filename.json", "r") as f:
        guildInfo = json.load(f)

    guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets channel to send message to as the channel the command was sent to

    with open("filename.json", "w") as f:
        json.dump(guildInfo, f)

然后就用

with open("filename.json", "r"):
    guildInfo = json.load(f)

channnel = guildInfo[ctx.message.guild.id]

获取发送消息的频道和

channel.send(embed=embed)

发送消息

在运行之前确保在同一目录中有一个空的json文件并将{}添加到文件中

before running it ensure to have an empty json file in the same directory and add {} to the file