Discord.py-机器人启动时加载公会前缀(MySQL)

时间:2020-11-02 19:04:24

标签: python discord.py

我有一个使用 discord.py mysql 的discord机器人,并且当前每次发送消息时都在加载行会前缀:

@client.event
async def on_message(message):

    cursor = mydb.cursor()
    cursor.execute(f"SELECT prefix FROM servers WHERE guild = {message.guild.id}")
    prefix = cursor.fetchone()[0]

问题在于该机器人正在变得越来越大,并且也越来越落后。因此,我想在机器人启动时在on_ready()事件中加载所有前缀。使用 discord.js ,会像这样:

const guildPrefixes = new Map();

client.on('ready', () => {

    client.guilds.cache.forEach(guild => {
        connection.query(
            `SELECT prefix FROM servers WHERE guild = '${guild.id}'`
        ).then(result => {
            guildPrefixes.set(guild.id, result[0][0].prefix);
        }).catch(err => console.log(err));
    });

});

client.on('message', async (message) => {

    const prefix = guildPrefixes.get(message.guild.id);
    // code here...

});

如何使用 discord.py 执行此操作? 预先谢谢你。

1 个答案:

答案 0 :(得分:0)

遍历client.guilds

下面是修改后的代码:

@client.event
async def on_ready():
    client.prefixes = {}
    for i in client.guilds:
        cursor = mydb.cursor()
        cursor.execute(f"SELECT prefix FROM servers WHERE guild = {i.id}")
        prefix = cursor.fetchone()[0]
        client.prefixes[i.id] = prefix

@client.event
async def on_message(m):
    prefix = client.prefixes.get(m.guild.id)
    # code