LoginSignup
0
4

Discord.pyで使用すべきライブラリ達

Last updated at Posted at 2024-02-25

はじめに

この記事は私のメモ的なものですので、読むなら軽く参照程度で構いません。

待機処理

asyncioモジュール、timeではDiscord API Gatewayへの接続が途切れてしまうためasyncioをつかう

main.py
import asyncio

# 中略

@bot.event
async def on_message(msg: discord.Message):
    if msg.content == "wait":
        await asyncio.sleep(5) # 一応コルーチンなのでawaitつける
        await msg.channel.send("waited")

音楽コマンドなどではasyncio.Queue()を使う

コード省略(←?)

データベース系

pymysqlが一般的だが非同期処理をするためaiomysqlを使う

main.py
import aiomysql
import aiomysql.cursors

id = 12345

async with aiomysql.connect(host="localhost", user="root", password="password", cursorclass=aiomysql.cursors.DictCursor) as conn:
    async with conn.cursor() as cur:
        await cur.execute("SELECT * FROM table WHERE id = %s", (id, ))
        result = await cur.fetchone()

aiomysqlでもプレースホルダーは使える。execute()に第一引数としてSQLクエリ(変数には%s)、第二引数としてプレースホルダーに代入する値をタプルで渡す
ちなみにプレースホルダーに代入する値が一つしかないとき、タプルは(変数, )のようにコンマを一つつける。

ファイル読み書き

こちらもビルドイン関数のopen()を使用せず、aiofilesを使用する。Discord.py上ではでっかいファイルを読み書きするときこれでハートブレイクを起こさずに済む。

main.py
import aiofiles
async with aiofiles("hoge.txt", "w", encoding="utf-8") as f:
    await f.write("Hello World!")

終わり

以上メモでした。チャンチャン

0
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4