Keyvでデータを保存する

Keyvopen in new window is a simple key-value store that works with multiple backends. Sharding に対応し、JSON ストレージをサポートしています。

インストール

npm install keyv
yarn add keyv
pnpm add keyv

Keyv requires an additional package depending on which persistent backend you would prefer to use. If you want to keep everything in memory, you can skip this part. Otherwise, install one of the below.

npm install @keyv/redis
npm install @keyv/mongo
npm install @keyv/sqlite
npm install @keyv/postgres
npm install @keyv/mysql
yarn add @keyv/redis
yarn add @keyv/mongo
yarn add @keyv/sqlite
yarn add @keyv/postgres
yarn add @keyv/mysql
pnpm add @keyv/redis
pnpm add @keyv/mongo
pnpm add @keyv/sqlite
pnpm add @keyv/postgres
pnpm add @keyv/mysql

Keyv と必要なドライバをインストールしたら Keyv のインスタンスを作成します。

const Keyv = require('keyv');

// 以下の中から一つを選択してください。
const keyv = new Keyv(); // for in-memory storage
const keyv = new Keyv('redis://user:pass@localhost:6379');
const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname');
const keyv = new Keyv('sqlite://path/to/database.sqlite');
const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname');
const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname');
1
2
3
4
5
6
7
8
9

接続エラーをハンドル

keyv.on('error', err => console.error('Keyv connection error:', err));
1

より詳細な設定は、Keyv readmeopen in new window をご覧ください。

使い方

Keyv は Mapopen in new window-like な API を提供しています。 ただし、set, get, delete, clear メソッドのみである。 さらに、これらのメソッドはデータをすぐに返すのではなく、データを Promises で返します。

(async () => {
    // true
    await keyv.set('foo', 'bar');

    // bar
    await keyv.get('foo');

    // undefined
    await keyv.clear();

    // undefined
    await keyv.get('foo');
})();
1
2
3
4
5
6
7
8
9
10
11
12
13

アプリケーション

Although Keyv can assist in any scenario where you need key-value data, we will focus on setting up a per-guild prefix configuration using Sqlite.

TIP

This section will still work with any provider supported by Keyv. We recommend PostgreSQL for larger applications.

セットアップ

const Keyv = require('keyv');
const { Client, Intents } = require('discord.js');
const { globalPrefix, token } = require('./config.json');

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const prefixes = new Keyv('sqlite://path/to.sqlite');
1
2
3
4
5
6

コマンドハンドラ

This guide uses a very basic command handler with some added complexity to allow for multiple prefixes. Look at the command handling guide for a more robust command handler.

client.on('messageCreate', async message => {
    if (message.author.bot) return;

    let args;
    // handle messages in a guild
    if (message.guild) {
        let prefix;

        if (message.content.startsWith(globalPrefix)) {
            prefix = globalPrefix;
        } else {
            // check the guild-level prefix
            const guildPrefix = await prefixes.get(message.guild.id);
            if (message.content.startsWith(guildPrefix)) prefix = guildPrefix;
        }

        // if we found a prefix, setup args; otherwise, this isn't a command
        if (!prefix) return;
        args = message.content.slice(prefix.length).trim().split(/\s+/);
    } else {
        // handle DMs
        const slice = message.content.startsWith(globalPrefix) ? globalPrefix.length : 0;
        args = message.content.slice(slice).split(/\s+/);
    }

    // get the first space-delimited argument after the prefix as the command
    const command = args.shift().toLowerCase();
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Prefix コマンド

Now that you have a command handler, you can make a command to allow people to use your prefix system.

client.on('messageCreate', async message => {
    // ...
    if (command === 'prefix') {
        // if there's at least one argument, set the prefix
        if (args.length) {
            await prefixes.set(message.guild.id, args[0]);
            return message.channel.send(`Successfully set prefix to \`${args[0]}\``);
        }

        return message.channel.send(`Prefix is \`${await prefixes.get(message.guild.id) || globalPrefix}\``);
    }
});


 
 
 
 
 
 
 
 
 

1
2
3
4
5
6
7
8
9
10
11
12

You will probably want to set up additional validation, such as required permissions and maximum prefix length.

使い方

ユーザー05/09/2022
.prefix
ガイドボット Bot 05/09/2022
Prefix は . です。
ユーザー05/09/2022
.prefix $
ガイドボット Bot 05/09/2022
Prefix を $ に設定しました。
ユーザー05/09/2022
$prefix
ガイドボット Bot 05/09/2022
Prefix は $ です。

次のステップ

Various other applications can use Keyv, such as guild settings; create another instance with a different namespaceopen in new window for each setting. Additionally, it can be extendedopen in new window to work with whatever storage backend you prefer.

Check out the Keyv repositoryopen in new window for more information.

最終的なコード

If you want to compare your code to the code we've constructed so far, you can review it over on the GitHub repository here open in new window.

Last Updated: 2022/4/19 3:48:55