LoginSignup
5
1

More than 3 years have passed since last update.

discord.py でよく躓くとこ(随時更新)

Last updated at Posted at 2020-12-08

はじめに

これはteratailとかDiscord Bot Portal JPの質問に回答していって「こういうの多いなぁ」って感じたり、自分が躓いたとこを貼るだけのやつです。
discord.py公式のよくある質問とかを見てからこの記事を読むのをおすすめします。

一般

Q. add_reactionがHTTPException吐く!ちゃんと:thinking:って書いたのに!
A. add_reactionで標準の絵文字を使うには🤔みたいにUnicodeの絵文字を引数に渡す必要があります。
🤔みたいなのをもってくるのに1番手っ取り早い方法はDiscordで\を絵文字の前につけて送信する方法です。(\:thinking:みたいに書いて送信すると、Unicodeの絵文字が送信されるからそれをコピペ)
「絵文字をソースコードに書きたくない!」って人はR.Dannyのcharinfoとかで\U0001f914みたいなやつをもってくるとか、emojiライブラリemoji.emojize(":thinking_face:", use_aliases=True)を使うとかしましょう。

Q. TextChannel.history、チャンネルID指定したのにAttributeエラー吐く!なんで!?
A. チャンネルIDはそのままだとただのクソデカ数値(正確にはsnowflakeっていう特殊なやつだけど)です。
client.get_channel(チャンネルID)(bot.get_channel(チャンネルID)の人もいるかも)でTextChannelオブジェクトを持ってきましょう。
(変えたらAttributeError:'NoneType' object has no attribute〜を吐くときは、チャンネルIDが間違ってる可能性があります。)

Embed

Q. timestampの時間ずれる!なんで!?
A. EmbedのtimestampはUTC指定です。
- datetime.datetime.now(datetime.timezone.utc)
- datetime.datetime.utcnow()
- datetime.timedelta(hours=9)をマイナスする(PCの時刻が日本なら)
でUTCになります。

commandsフレームワーク

Q. コマンド動かない!ちゃんとon_message を使うとコマンドが動作しなくなります。どうしてですか。のやつ入れたのに! or process_commands入れたらグローバルチャット(とかあいさつとか)動かない!

A. グローバルチャット(とかあいさつとか)用とprocess_commands用でon_messageを2個おいてませんか?
最後に定義した方だけ実行されます。
process_commandsのon_messageを消して、
もう片方のon_messageにawait bot.process_commands(message)
(それかawait client.process_commands(message)みたいな)を書きましょう。

Q. よくある質問のbot.process_commands(message)入れたらNameError: name 'bot' is not defined出たんだけど!?
A. botではなくclientっていう名前の変数にcommands.Bot入れてませんか?(client = commands.Bot(色々)

await client.process_commands(message)

にしてみましょう。

coroutine関係

Q. time.sleepしたらBot全体が止まるんだけど!
A. asyncio.sleepを使ってみましょう。

import discord
import asyncio # ← 重要
# ~~~~~
@client.event
async def on_message(message):
  if message.author.bot:
    return
  # ~~~~~
  if message.content == "起きろ":
    msg = await message.channel.send("(。-ω-)zzz")
    await asyncio.sleep(5)
    await msg.edit(content="(。゚ω゚) ハッ!")

最後に

ここで解決できなくて、teratailとかで質問しようと思っているそこのあなた。
1つだけ覚えておいて欲しいことがあります。
「tracebackとコードは全文貼って。」
teratailが用意しているテンプレートを使えば回答率が結構上がります。(多分)
これを忘れないようにしておきましょう。

最後まで読んでくれてありがとうございました。
もしここで解決したならLGTMしてね()

5
1
0

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
5
1