はじめに
discordに名言を流すだけのbotを作りました.
名言がぱっと出てくると日常会話が楽しいと思うので,暇な時に名言でも見て覚えようかと.
名言をランダムに返す無料のAPIがあるんですね.それが今回一番の驚きでした.
実装
基本設定
見たい人もいるかもしれないので一応
import discord
import random
import json
import http.client
with open('Secret.txt', 'r') as file:
lines = file.readlines()
secret_token = lines[0].strip().split(':')[1]
intents = discord.Intents.all()
client = discord.Client(intents=intents)
名言を取得
今回使用させていただいたAPIは以下の2つ.
英語の名言のAPI: quotable
日本語の名言のAPI: 「名言教えるよ!」のサイト
英語版もそうですが,まさか日本語版まで名言のAPIがあるとは……
どちらもシンプルな実装で大変使いやすいです.
「名言教えるよ!」のサイトはAPIもそうですが,webサイトの実装が面白かったです.
def get_quote(lang='jp'):
if lang == 'jp':
conn = http.client.HTTPSConnection("meigen.doodlenote.net")
conn.request("GET", "/api/json.php")
res = conn.getresponse()
data = res.read()
quote_data = json.loads(data.decode("utf-8"))[0]
return f"{quote_data['meigen']} - {quote_data['auther']}"
elif lang == 'en':
conn = http.client.HTTPSConnection("api.quotable.io")
conn.request("GET", "/random")
res = conn.getresponse()
data = res.read()
quote_data = json.loads(data.decode("utf-8"))
return f"{quote_data['content']} - {quote_data['author']}"
残りの実装
!quoteと送信すると明言が返ってきます.それだけ.
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!quote'):
if message.content.startswith('!quoteen'):
quote = get_quote('en')
print(quote)
await message.channel.send(quote)
else:
quote = get_quote()
print(quote)
await message.channel.send(quote)
client.run(secret_token)
結果
!quote
与えてください。あなたの心が痛むほどに。 - マザー・テレサ
!quoteen
But I'll tell you what hermits realize. If you go off into a far, far forest and get very quiet, you'll come to understand that you're connected with everything. - Alan Watts
いい感じ.
毎回 !quote と打つのも面倒なので,定期的に自動で名言を流すようにしてもいいかもしれません.