Skip to content

Instantly share code, notes, and snippets.

@r74tech
Created July 30, 2021 16:06
Show Gist options
  • Save r74tech/8cbc4990b27b66ec63a9e91a8c1105a5 to your computer and use it in GitHub Desktop.
Save r74tech/8cbc4990b27b66ec63a9e91a8c1105a5 to your computer and use it in GitHub Desktop.
discord.pyでpollをわかりやすく表示しよう
import discord
from discord.ext import commands
class poll(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def poll(self, ctx, *args):
text = "**{}**".format(args[0])
n = len(args)-1
if(n == 0):
return
if(n > 10):
await ctx.reply("選択肢は10個以下にしてください")
return
emojis = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"]
embed = discord.Embed()
for i in range(n):
embed.add_field(name=emojis[i]+" "+args[i+1], value="投票待ち", inline=False)
message = await ctx.reply(text,embed=embed)
for i in range(n):
await message.add_reaction(emojis[i])
@commands.Cog.listener()
async def on_raw_reaction_add(self, reaction):
if reaction.member.bot:
return
else:
channel = self.bot.get_channel(reaction.channel_id)
message = await channel.fetch_message(reaction.message_id)
embed, emojis = message.embeds[0], ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"]
index = emojis.index(reaction.emoji.name)
if embed.fields[index].value == "投票待ち":
embed.set_field_at(index, name=embed.fields[index].name, value=reaction.member.mention, inline=False)
elif reaction.member.mention in embed.fields[index].value:
return
else:
embed.set_field_at(index, name=embed.fields[index].name, value=embed.fields[index].value+" "+reaction.member.mention, inline=False)
await message.edit(embed=embed)
@commands.Cog.listener()
async def on_raw_reaction_remove(self, reaction):
channel = self.bot.get_channel(reaction.channel_id)
message = await channel.fetch_message(reaction.message_id)
embed, emojis = message.embeds[0], ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"]
index = emojis.index(reaction.emoji.name)
guild = self.bot.get_guild(reaction.guild_id)
remove_usr = guild.get_member(reaction.user_id)
if " " in embed.fields[index].value:
mention = embed.fields[index].value.split()
mention.remove(remove_usr.mention)
mention = " ".join(mention)
embed.set_field_at(index, name=embed.fields[index].name, value=mention, inline=False)
elif embed.fields[index].value == remove_usr.mention:
embed.set_field_at(index, name=embed.fields[index].name, value="投票待ち", inline=False)
else:
return
await message.edit(embed=embed)
def setup(bot):
bot.add_cog(poll(bot))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment