add providers

This commit is contained in:
Romain J 2019-10-14 00:12:47 +02:00
parent d00aadd82f
commit fdc9c9196d
7 changed files with 86 additions and 96 deletions

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
@ -25,7 +24,7 @@ class Polls(commands.Cog):
if poll.count() != 0:
poll = poll.one()
emotes = utils_emotes.get(len(poll.responses))
emotes = utils_emotes.get(len(poll.choice))
if pld.emoji.name in emotes:
return poll
@ -39,6 +38,73 @@ 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
)
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 +168,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 +178,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,3 +1,3 @@
from .lang import Lang
from .warn import Warn
from .poll import Poll
from .poll import Poll, Responses

View file

@ -1,6 +1,7 @@
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
from werkzeug.security import generate_password_hash, check_password_hash
Base = declarative_base()
@ -13,7 +14,9 @@ class Poll(Base):
message_id = Column(BigInteger)
content = Column(JSON)
is_anonymous = Column(Boolean)
available_choices = Column(Integer)
choice = relationship("Responses")
@ -21,7 +24,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)

1
output.txt Normal file

File diff suppressed because one or more lines are too long

View file

@ -1,11 +1,11 @@
{
"280805240977227776": [
"b!"
"b!!"
],
"303633056944881686": [
"b!"
"b!!"
],
"336642139381301249": [
"b!"
"b!!"
]
}

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