Discord公式APIのラッパー、Discord.py を利用して、グローバルチャットを作成してみます。
グローバルチャットとは?
理解が合っているのかも不明ですが、例えばA、B、Cの3つのDiscordサーバーがあったとき、Aサーバーに投稿するとその内容がBサーバー、Cサーバーに転送され、Bサーバーに投稿すれば内容はAサーバーとCサーバーに・・・というものです。
一部のDiscordサーバーで行われているようですが、そこまで有名ではないかもしれない(自分も最近まで知らなかった)
そこまで難しくなさそうなので実装してみましょう。
実装
基本
見栄え的に、アイコンや名前を変えられるWebhookを使って実装することが多いようですが、まずはbotアカウントで送信させてみます。
import discord client = discord.Client() @client.event async def on_ready(): client.global_list = []#グローバルチャット参加チャンネルのリスト @client.event async def on_message(message): if message.author == message.guild.me: return if message.content == "!global": if message.channel not in client.global_list: client.global_list.append(message.channel) await message.channel.send("グローバルチャットのチャンネルに登録しました。") else: await message.channel.send("既に登録されています。") return embed = discord.Embed(title=f"サーバー: {message.guild.name}",description=message.clean_content ) embed.set_author(name=message.author.name,icon_url=message.author.avatar_url) for ch in client.global_list: if message.channel != ch: await ch.send(embed=embed) client.run("token")
Webhook使用版
Webhookを使えばアイコンとかを変えられます。
import discord client = discord.Client() @client.event async def on_ready(): client.global_list = [] @client.event async def on_message(message): if message.author == message.guild.me: return if message.webhook_id: return global_tmp = [w for w in await message.channel.webhooks() if w in client.global_list] if message.content == "!global": if global_tmp: await message.channel.send("既に登録されています。") return new_w = await message.channel.create_webhook(name="global") client.global_list.append(new_w) await message.channel.send("グローバルチャットのチャンネルに登録しました。") return for webhook in client.global_list: if message.channel != webhook.channel: await webhook.send(content=message.content,username=message.author.name,avatar_url=message.author.avatar_url) client.run(token)
応用
特定の名前のチャンネルを作成することでその名前からグローバルチャット用のチャンネルを検索できるようにします。
import discord client = discord.Client() @client.event async def on_ready(): client.global_list = [] #グローバルチャット参加チャンネルのリスト for guild in client.guilds: tmp = discord.utils.get(guild.text_channels,name="global_test") if tmp: client.global_list.append(tmp) @client.event async def on_message(message): if message.author == message.guild.me: return if message.content == "!global": if discord.utils.get(message.guild.text_channels,name="global_test"): await message.channel.send("既に参加しています。") return ch = await message.guild.create_text_channel("global_test") client.global_list.append(ch) return embed = discord.Embed(title=f"サーバー: {message.guild.name}",description=message.clean_content ) embed.set_author(name=message.author.name,icon_url=message.author.avatar_url) if message.channel in client.global_list: for ch in client.global_list: if message.guild != ch.guild: await ch.send(embed=embed) client.run('token')
起動時にglobal_test
チャンネルがあればそれを対象に追加します。
!global
と送信されたら、global_test
チャンネルを作成しそれを対象に追加します。
おわり
この記事ではよくあるグローバルチャットの機能を全て実装できているわけではないと思います。 それでも作成の第一歩の一助となれば幸いです。