This commit is contained in:
Romain J 2019-10-26 23:19:47 +02:00
parent d00aadd82f
commit c6114709ee
7 changed files with 88 additions and 94 deletions

2
bot.py
View file

@ -31,7 +31,7 @@ l_extensions = (
async def _prefix_callable(bot, message: discord.message) -> list:
extras = []
extras = ['.']
if message.guild is not None:
extras = bot.prefixes.get(str(message.guild.id), [])

View file

@ -137,7 +137,8 @@ class Basics(commands.Cog):
inline=False
)
e.set_footer(text=f'version: {self.bot.version}')
e.set_footer(text=f'version: {self.bot.version} '
f'• prefix: {ctx.prefix}')
await ctx.send(embed=e)

View file

@ -2,13 +2,12 @@ import json
from typing import Union
import discord
import bcrypt
from discord.ext import commands
from yarl import URL
from bot import TuxBot
from .utils.lang import Texts
from .utils.models import Poll
from .utils.models import Poll, Responses
from .utils import emotes as utils_emotes
@ -23,9 +22,11 @@ class Polls(commands.Cog):
.query(Poll) \
.filter(Poll.message_id == pld.message_id)
print("-------------------------25---------------------------")
if poll.count() != 0:
print("-------------------------27---------------------------")
poll = poll.one()
emotes = utils_emotes.get(len(poll.responses))
emotes = utils_emotes.get(poll.available_choices)
if pld.emoji.name in emotes:
return poll
@ -39,6 +40,76 @@ class Polls(commands.Cog):
await message.remove_reaction(pld.emoji.name, user)
@commands.Cog.listener()
async def on_raw_reaction_add(self, pld: discord.RawReactionActionEvent):
poll = self.get_poll(pld)
if poll:
if poll.is_anonymous:
try:
await self.remove_reaction(pld)
except discord.errors.Forbidden:
pass
choice = utils_emotes.get_index(pld.emoji.name)
response = self.bot.database.session.query(Poll) \
.filter(
Responses.poll_id == poll.id,
Responses.user == pld.user_id,
Responses.choice == choice
)
print(pld.user_id, poll.id, choice)
if response.count() != 0:
response = response.one()
self.bot.database.session.delete(response)
else:
response = Responses(
user=pld.user_id,
poll_id=poll.id,
choice=choice
)
self.bot.database.session.add(response)
self.bot.database.session.commit()
"""---------------------------------------------------------------------"""
async def create_poll(self, ctx: commands.Context, poll: str, anonymous):
question = (poll.split('|')[0]).strip()
responses = [response.strip() for response in poll.split('|')[1:]]
emotes = utils_emotes.get(len(responses))
stmt = await ctx.send(Texts('poll', ctx).get('**Preparation...**'))
poll_row = Poll()
self.bot.database.session.add(poll_row)
self.bot.database.session.flush()
e = discord.Embed(description=f"**{question}**")
e.set_author(
name=self.bot.user if anonymous else ctx.author,
icon_url="https://cdn.gnous.eu/tuxbot/survey1.png"
)
for i, response in enumerate(responses):
e.add_field(
name=f"{emotes[i]} __{response.capitalize()}__",
value="**0** vote"
)
e.set_footer(text=f"ID: {poll_row.id}")
poll_row.channel_id = stmt.channel.id
poll_row.message_id = stmt.id
poll_row.content = e.to_dict()
poll_row.is_anonymous = anonymous
poll_row.available_choices = len(responses)
self.bot.database.session.commit()
await stmt.edit(content='', embed=e)
for emote in range(len(responses)):
await stmt.add_reaction(emotes[emote])
async def update_poll(self, poll_id: int):
poll = self.bot.database.session \
.query(Poll) \
@ -102,86 +173,6 @@ class Polls(commands.Cog):
poll.content = json.dumps(content)
self.bot.database.session.commit()
@commands.Cog.listener()
async def on_raw_reaction_add(self, pld: discord.RawReactionActionEvent):
poll = self.get_poll(pld)
if poll:
if poll.is_anonymous:
try:
await self.remove_reaction(pld)
except discord.errors.Forbidden:
pass
user_id = str(pld.user_id).encode()
choice = utils_emotes.get_index(pld.emoji.name) + 1
responses = json.loads(poll.responses) \
if isinstance(poll.responses, str) \
else poll.responses
if not responses.get(str(choice)):
user_id_hash = bcrypt.hashpw(user_id, bcrypt.gensalt())
responses \
.get(str(choice)) \
.append(user_id_hash.decode())
else:
for i, responder in enumerate(responses.get(str(choice))):
if bcrypt.checkpw(user_id, responder.encode()):
responses \
.get(str(choice)) \
.pop(i)
break
else:
user_id_hash = bcrypt.hashpw(user_id, bcrypt.gensalt())
responses \
.get(str(choice)) \
.append(user_id_hash.decode())
break
poll.responses = json.dumps(responses)
self.bot.database.session.commit()
await self.update_poll(poll.id)
"""---------------------------------------------------------------------"""
async def make_poll(self, ctx: commands.Context, poll: str, anonymous):
question = (poll.split('|')[0]).strip()
responses = [response.strip() for response in poll.split('|')[1:]]
responses_row = {}
emotes = utils_emotes.get(len(responses))
stmt = await ctx.send(Texts('poll', ctx).get('**Preparation...**'))
poll_row = Poll()
self.bot.database.session.add(poll_row)
self.bot.database.session.flush()
e = discord.Embed(description=f"**{question}**")
e.set_author(
name=self.bot.user if anonymous else ctx.author,
icon_url="https://cdn.gnous.eu/tuxbot/survey1.png"
)
for i, response in enumerate(responses):
responses_row[str(i + 1)] = []
e.add_field(
name=f"{emotes[i]} __{response.capitalize()}__",
value="**0** vote"
)
e.set_footer(text=f"ID: {poll_row.id}")
poll_row.message_id = stmt.id
poll_row.channel_id = stmt.channel.id
poll_row.content = e.to_dict()
poll_row.is_anonymous = anonymous
poll_row.responses = responses_row
self.bot.database.session.commit()
await stmt.edit(content='', embed=e)
for emote in range(len(responses)):
await stmt.add_reaction(emotes[emote])
@commands.group(name='sondage', aliases=['poll'])
async def _poll(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
@ -192,7 +183,7 @@ class Polls(commands.Cog):
is_anonymous = '--anonyme' in poll
poll = poll.replace('--anonyme', '')
await self.make_poll(ctx, poll, anonymous=is_anonymous)
await self.create_poll(ctx, poll, anonymous=is_anonymous)
def setup(bot: TuxBot):

View file

@ -1,5 +1,5 @@
emotes = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟', '0⃣',
'🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮']
'🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮']
def get(count):
@ -7,4 +7,4 @@ def get(count):
def get_index(emote):
return emotes.index(emote)
return emotes.index(emote)

View file

@ -1,3 +1,3 @@
from .lang import Lang
from .warn import Warn
from .poll import Poll
from .poll import Poll, Responses

View file

@ -1,5 +1,5 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Text, BigInteger, JSON, ForeignKey
from sqlalchemy import Column, Integer, BigInteger, JSON, ForeignKey, Boolean
from sqlalchemy.orm import relationship
Base = declarative_base()
@ -13,7 +13,9 @@ class Poll(Base):
message_id = Column(BigInteger)
content = Column(JSON)
is_anonymous = Column(Boolean)
available_choices = Column(Integer)
choice = relationship("Responses")
@ -21,7 +23,7 @@ class Responses(Base):
__tablename__ = 'responses'
id = Column(Integer, primary_key=True, autoincrement=True)
user = Column(Text)
user = Column(BigInteger)
poll_id = Column(Integer, ForeignKey('polls.id'))
choice = Column(Integer)

View file

@ -3,11 +3,11 @@ discord.py[voice]
jishaku
lxml
click
asyncpg>=0.12.0
asyncpg
sqlalchemy
gitpython
requests
psutil
bcrypt
werkzeug
tcp_latency
yarl
yarl