Esempio n. 1
0
 async def on_message(self, message: discord.Message):
     if not message.attachments or message.guild is None:
         return
     images9000 = []
     for attachment in message.attachments:
         if attachment.height and attachment.width:
             image_bytes = io.BytesIO()
             try:
                 await attachment.save(image_bytes)
             except (discord.HTTPException, discord.NotFound):
                 continue
             else:
                 try:
                     hash_string = self._hash(image_bytes)
                 except:
                     continue
                 images9000.append(
                     Image9000(
                         attachment_id=attachment.id,
                         message_id=message.id,
                         user_id=message.author.id,
                         channel_id=message.channel.id,
                         server_id=message.guild.id,
                         hash=hash_string,
                         sent_at=utc_to_naive_local(message.created_at),
                     ))
     try:
         with data.session(commit=True) as session:
             session.bulk_save_objects(images9000)
     except (psycopg2.errors.ForeignKeyViolation,
             psycopg2.errors.UniqueViolation):
         pass
Esempio n. 2
0
 async def restore(self, ctx):
     """Reverts to the default command prefix."""
     self.bot.prefixes[ctx.guild.id] = ()
     with data.session(commit=True) as session:
         data_server = session.query(data.Server).get(ctx.guild.id)
         previous_prefixes = data_server.command_prefix.split(
             '|') if data_server.command_prefix else ()
         data_server.command_prefix = None
     if not previous_prefixes:
         embed = self.bot.generate_embed(
             'ℹ️', 'Już ustawiony jest prefiks domyślny')
         embed.add_field(
             name='Wartość',
             value=f'domyślna `{configuration["command_prefix"]}`')
     else:
         embed = self.bot.generate_embed('✅',
                                         'Przywrócono domyślny prefiks')
         embed.add_field(
             name='Nowa wartość',
             value=f'domyślna `{configuration["command_prefix"]}`')
         embed.add_field(name='Poprzednia wartość' if len(previous_prefixes)
                         == 1 else 'Poprzednie wartości',
                         value=' lub '.join(
                             (f'`{prefix}`'
                              for prefix in reversed(previous_prefixes))),
                         inline=False)
     embed.add_field(
         name='Przykłady wywołań',
         value=
         f'`{configuration["command_prefix"]}wersja` lub `{configuration["command_prefix"]} oof` '
         f'lub `{ctx.me} urodziny`',
         inline=False)
     await self.bot.send(ctx, embed=embed)
Esempio n. 3
0
 async def oof_server(self, ctx):
     async with ctx.typing():
         with data.session() as session:
             total_oofs = session.query(
                 data.func.sum(Oofer.oofs).filter(
                     Oofer.server_id == ctx.guild.id)).scalar()
             top_results = (session.query(
                 Oofer,
                 data.func.dense_rank().over(
                     order_by=Oofer.oofs.desc()).label('rank')).filter(
                         Oofer.server_id == ctx.guild.id).limit(25).all())
         ranking = []
         for result in top_results:
             if result.rank > 10:
                 break
             ranking.append(
                 f'{result.rank}. <@{result.Oofer.user_id}> – '
                 f'{word_number_form(result.Oofer.oofs, "oofnięcie", "oofnięcia", "oofnięć")}'
             )
         if total_oofs:
             notice = f'Do tej pory oofnięto na serwerze {word_number_form(total_oofs, "raz", "razy")}'
         else:
             notice = 'Na serwerze nie oofnięto jeszcze ani razu'
         embed = self.bot.generate_embed('💨', notice)
         if ranking:
             embed.add_field(name='Najaktywniejsi ooferzy',
                             value='\n'.join(ranking),
                             inline=False)
         await self.bot.send(ctx, embed=embed)
Esempio n. 4
0
 async def on_ready(self):
     with data.session() as session:
         for reminder in session.query(Reminder).filter(Reminder.has_been_executed == False):
             self.bot.loop.create_task(self.set_off_reminder(
                 reminder.confirmation_message_id, reminder.channel_id, reminder.user_id,
                 reminder.content, reminder.requested_at, reminder.execute_at
             ))
Esempio n. 5
0
 async def on_ready(self):
     psutil.cpu_percent()
     localize()
     self.ready_datetime = dt.datetime.now()
     self.session = aiohttp.ClientSession(loop=self.loop, headers=self.HEADERS)
     self.ch_client = ChClient(
         self.session,
         url=configuration["clickhouse_url"],
         user=configuration["clickhouse_user"],
         password=configuration["clickhouse_password"],
         database="somsiad",
     )
     assert await self.ch_client.is_alive()
     print('Przygotowywanie danych serwerów...')
     data.Server.register_all(self.guilds)
     with data.session(commit=True) as session:
         for server in session.query(data.Server):
             self.prefixes[server.id] = tuple(server.command_prefix.split('|')) if server.command_prefix else ()
             if server.joined_at is None:
                 discord_server = self.get_guild(server.id)
                 if discord_server is not None and discord_server.me is not None:
                     server.joined_at = utc_to_naive_local(discord_server.me.joined_at)
     self.system_channel = cast(Optional[discord.TextChannel], await self.fetch_channel(517422572615499777))  # magic
     self.public_channel = cast(Optional[discord.TextChannel], await self.fetch_channel(479458695126974466))  # magic
     self.loop.create_task(self.cycle_presence())
     await self.system_notify('✅', 'Włączyłem się')
     self.print_info()
Esempio n. 6
0
 async def birthday_when(self, ctx, *, member: discord.Member = None):
     member = member or ctx.author
     with data.session() as session:
         born_person = session.query(BornPerson).get(member.id)
         if born_person is None or born_person.birthday is None:
             if member == ctx.author:
                 address = 'Nie ustawiłeś'
             else:
                 address = f'{member} nie ustawił'
             embed = discord.Embed(
                 title=f':question: {address} swojej daty urodzin',
                 color=self.bot.COLOR)
         elif not born_person.is_birthday_public(session, ctx.guild):
             if member == ctx.author:
                 address = 'Nie upubliczniłeś'
             else:
                 address = f'{member} nie upublicznił'
             embed = discord.Embed(
                 title=
                 f':question: {address} na tym serwerze swojej daty urodzin',
                 color=self.bot.COLOR)
         else:
             emoji = 'birthday' if born_person.is_birthday_today(
             ) else 'calendar_spiral'
             address = 'Urodziłeś' if member == ctx.author else f'{member} urodził'
             date_presentation = born_person.birthday.strftime(
                 '%-d %B' if born_person.birthday.year ==
                 BornPerson.EDGE_YEAR else '%-d %B %Y')
             embed = discord.Embed(
                 title=f':{emoji}: {address} się {date_presentation}',
                 color=self.bot.COLOR)
     return await self.bot.send(ctx, embed=embed)
Esempio n. 7
0
 async def birthday_make_secret(self, ctx):
     with data.session(commit=True) as session:
         born_person = session.query(BornPerson).get(ctx.author.id)
         this_server = session.query(data.Server).get(ctx.guild.id)
         if born_person is None or born_person.birthday is None:
             embed = self.bot.generate_embed(
                 'ℹ️',
                 'Nie ustawiłeś swojej daty urodzin, więc nie ma czego utajniać'
             )
         elif this_server not in born_person.birthday_public_servers:
             birthday_public_servers_presentation = ' '.join(
                 filter(
                     None,
                     self._get_birthday_public_servers_presentation(
                         born_person, on_server_id=ctx.guild.id)))
             embed = self.bot.generate_embed(
                 'ℹ️', 'Twoja data urodzin już jest tajna na tym serwerze',
                 birthday_public_servers_presentation)
         else:
             born_person.birthday_public_servers.remove(this_server)
             birthday_public_servers_presentation = ' '.join(
                 filter(
                     None,
                     self._get_birthday_public_servers_presentation(
                         born_person, on_server_id=ctx.guild.id)))
             embed = self.bot.generate_embed(
                 '🕵️‍♂️', 'Utajniono twoją datę urodzin na tym serwerze',
                 birthday_public_servers_presentation)
     await self.bot.send(ctx, embed=embed)
Esempio n. 8
0
 async def set_off_reminder(
         self, confirmation_message_id: int, channel_id: int, user_id: int, content: str,
         requested_at: dt.datetime, execute_at: dt.datetime
 ):
     if confirmation_message_id in self.reminders_set_off:
         return
     self.reminders_set_off.add(confirmation_message_id)
     await discord.utils.sleep_until(execute_at.astimezone())
     if confirmation_message_id not in self.reminders_set_off:
         return
     self.reminders_set_off.remove(confirmation_message_id)
     channel = self.bot.get_channel(channel_id)
     try:
         confirmation_message = await channel.fetch_message(confirmation_message_id)
     except (AttributeError, discord.NotFound):
         pass
     else:
         reminder_description = md_link(
             f'Przypomnienie z {human_datetime(requested_at)}.', confirmation_message.jump_url
         )
         reminder_embed = self.bot.generate_embed('🍅', content, reminder_description)
         reminder_message = await channel.send(f'<@{user_id}>', embed=reminder_embed)
         confirmation_description = md_link(
             f'Przypomniano ci tutaj "{content}" {human_datetime()}.', reminder_message.jump_url
         )
         confirmation_embed = self.bot.generate_embed('🍅', 'Zrealizowano przypomnienie', confirmation_description)
         await confirmation_message.edit(embed=confirmation_embed)
     with data.session(commit=True) as session:
         reminder = session.query(Reminder).get(confirmation_message_id)
         reminder.has_been_executed = True
Esempio n. 9
0
 async def pardon(self, ctx, subject_user: discord.Member):
     """Clears specified member's warnings."""
     with data.session(commit=True) as session:
         warning_deleted_count = (session.query(Event).filter(
             Event.server_id == ctx.guild.id,
             Event.user_id == subject_user.id,
             Event.type == 'warned').delete())
         if warning_deleted_count:
             warning_form = word_number_form(warning_deleted_count,
                                             'ostrzeżenie', 'ostrzeżenia',
                                             'ostrzeżeń')
             emoji = '✅'
             notice = f'Usunięto {warning_form} {subject_user}'
             event = Event(
                 type='pardoned',
                 server_id=ctx.guild.id,
                 channel_id=ctx.channel.id,
                 user_id=subject_user.id,
                 executing_user_id=ctx.author.id,
                 details=warning_form,
             )
             session.add(event)
         else:
             emoji = 'ℹ️'
             notice = f'{subject_user} nie ma na ostrzeżeń do usunięcia'
     await self.bot.send(ctx, embed=self.bot.generate_embed(emoji, notice))
Esempio n. 10
0
 async def ban(self, ctx, subject_user: discord.Member, *, reason):
     """Bans the specified member."""
     if reason and len(reason) > Event.MAX_DETAILS_LENGTH:
         return await self.bot.send(
             ctx,
             embed=self.bot.generate_embed(
                 '⚠️', f'Powód musi zawierać się w 1000 znaków lub mniej.'))
     try:
         await subject_user.ban(reason=reason)
     except discord.Forbidden:
         return await self.bot.send(
             ctx,
             embed=self.bot.generate_embed(
                 '⚠️', 'Bot nie może zbanować tego użytkownika'))
     else:
         with data.session(commit=True) as session:
             event = Event(type='banned',
                           server_id=ctx.guild.id,
                           channel_id=ctx.channel.id,
                           user_id=subject_user.id,
                           executing_user_id=ctx.author.id,
                           details=reason)
             session.add(event)
         return await self.bot.send(ctx,
                                    embed=self.bot.generate_embed(
                                        '✅', f'Zbanowano {subject_user}'))
Esempio n. 11
0
 async def burn(self, ctx, execute_at: interpret_str_as_datetime):
     """Removes the message after a specified mount time."""
     confirmation_description = (
         md_link(f'**Zostanie ona usunięta {human_datetime(execute_at)}.**',
                 ctx.message.jump_url) +
         '\n*Spalenie zostanie anulowane jeśli usuniesz tę wiadomość. Możesz to zrobić przy użyciu komendy `nie`.*'
     )
     confirmation_embed = self.bot.generate_embed('🔥',
                                                  f'Spalę twoją wiadomość',
                                                  confirmation_description)
     confirmation_message = await self.bot.send(ctx,
                                                embed=confirmation_embed)
     if confirmation_message is None:
         return
     try:
         details = {
             'confirmation_message_id': confirmation_message.id,
             'target_message_id': ctx.message.id,
             'channel_id': ctx.channel.id,
             'user_id': ctx.author.id,
             'requested_at': utc_to_naive_local(ctx.message.created_at),
             'execute_at': execute_at,
         }
         with data.session(commit=True) as session:
             reminder = Burning(**details)
             session.add(reminder)
             self.bot.loop.create_task(self.set_off_burning(**details))
     except:
         await confirmation_message.delete()
         raise
Esempio n. 12
0
 async def birthday_list(self, ctx):
     with data.session() as session:
         born_persons: List[BornPerson] = (session.query(BornPerson).join(
             BornPerson.birthday_public_servers).filter_by(
                 id=ctx.guild.id).all())
         if not born_persons:
             embed = discord.Embed(
                 title=
                 f':question: Żaden użytkownik nie upublicznił na tym serwerze daty urodzin',
                 color=self.bot.COLOR,
             )
         else:
             embed = discord.Embed(
                 title=
                 f'🗓 {word_number_form(len(born_persons), "użytkownik upublicznił", "użytkownicy upublicznili", "użytkowników upubliczniło")} na tym serwerze swoją datę urodzin',
                 color=self.bot.COLOR,
             )
             born_persons_filtered_sorted = sorted(
                 (person for person in born_persons if person.birthday),
                 key=lambda person: person.birthday.strftime('%m-%d-%Y'),
             )
             for born_person in born_persons_filtered_sorted:
                 user = born_person.discord_user(bot=ctx.bot)
                 date_presentation = born_person.birthday.strftime(
                     '%-d %B' if born_person.birthday.year ==
                     BornPerson.EDGE_YEAR else '%-d %B %Y')
                 embed.add_field(name=str(user),
                                 value=date_presentation,
                                 inline=True)
     return await self.bot.send(ctx, embed=embed)
Esempio n. 13
0
 async def warn(self, ctx, subject_user: discord.Member, *, reason):
     """Warns the specified member."""
     if reason and len(reason) > Event.MAX_DETAILS_LENGTH:
         return await self.bot.send(
             ctx,
             embed=self.bot.generate_embed(
                 '⚠️', f'Powód musi zawierać się w 1000 znaków lub mniej.'))
     with data.session(commit=True) as session:
         warning_count_query = session.query(Event).filter(
             Event.server_id == ctx.guild.id,
             Event.user_id == subject_user.id,
             Event.type == 'warned').statement.with_only_columns(
                 [data.func.count()])
         warning_count = session.execute(warning_count_query).scalar() + 1
         event = Event(type='warned',
                       server_id=ctx.guild.id,
                       channel_id=ctx.channel.id,
                       user_id=subject_user.id,
                       executing_user_id=ctx.author.id,
                       details=reason)
         session.add(event)
     return await self.bot.send(
         ctx,
         embed=self.bot.generate_embed(
             '✅', f'Ostrzeżono {subject_user} po raz {warning_count}.'))
Esempio n. 14
0
 async def remind(
         self, ctx, execute_at: interpret_str_as_datetime, *,
         content: commands.clean_content(fix_channel_mentions=True)
 ):
     if len(content) > Reminder.MAX_CONTENT_LENGTH:
         raise commands.BadArgument
     description = (
         f'**Przypomnę ci tutaj "{content}" {human_datetime(execute_at)}.**\n*Przypomnienie zostanie anulowane '
         'jeśli usuniesz tę wiadomość. Możesz to zrobić przy użyciu komendy `nie`.*'
     )
     embed = self.bot.generate_embed('🍅', 'Ustawiono przypomnienie', description)
     confirmation_message = await self.bot.send(ctx, embed=embed)
     if confirmation_message is None:
         return
     try:
         details = {
             'confirmation_message_id': confirmation_message.id, 'channel_id': ctx.channel.id, 'content': content,
             'user_id': ctx.author.id, 'requested_at': utc_to_naive_local(ctx.message.created_at),
             'execute_at': execute_at
         }
         with data.session(commit=True) as session:
             reminder = Reminder(**details)
             session.add(reminder)
             self.bot.loop.create_task(self.set_off_reminder(**details))
     except:
         await confirmation_message.delete()
         raise
Esempio n. 15
0
 async def send_all_birthday_today_notifications(self):
     with data.session(commit=True) as session:
         birthday_notifiers = session.query(BirthdayNotifier).all()
         for birthday_notifier in birthday_notifiers:
             if birthday_notifier.channel_id is not None:
                 await self.send_server_birthday_notifications(
                     birthday_notifier)
Esempio n. 16
0
 async def pins_archive(self, ctx):
     """Archives pins in the channel where the command was invoked."""
     async with ctx.typing():
         with data.session() as session:
             pin_archive = session.query(PinArchive).get(ctx.guild.id)
             description = None
             if pin_archive is None or pin_archive.channel_id is None:
                 emoji, notice = '⚠️', 'Nie ustawiono na serwerze kanału archiwum przypiętych wiadomości'
             elif pin_archive.discord_channel(self.bot) is None:
                 emoji, notice = '⚠️', 'Ustawiony kanał archiwum przypiętych wiadomości już nie istnieje'
             elif channel_being_processed_for_servers.get(
                     ctx.guild.id) is not None:
                 emoji, notice = (
                     '🔴',
                     'Na serwerze właśnie trwa przetwarzanie kanału '
                     f'#{channel_being_processed_for_servers[ctx.guild.id]}',
                 )
             else:
                 channel_being_processed_for_servers[
                     ctx.guild.id] = pin_archive.discord_channel(self.bot)
                 try:
                     try:
                         async with channel_being_processed_for_servers[
                                 ctx.guild.id].typing():
                             archivization_counts = await pin_archive.archive(
                                 self.bot, ctx.channel)
                     except ValueError:
                         emoji, notice = '🔴', 'Brak przypiętych wiadomości do zarchiwizowania'
                     except PinArchive.ChannelNotFound:
                         emoji, notice = '⚠️', 'Musisz ustawić nowy kanał archiwum przypiętych wiadomości'
                     else:
                         pinned_forms = ('przypiętą wiadomość',
                                         'przypięte wiadomości',
                                         'przypiętych wiadomości')
                         emoji = '✅'
                         notice = (
                             'Zarchiwizowano '
                             f'{word_number_form(archivization_counts["successful"], *pinned_forms)}'
                         )
                         description_parts = []
                         forms = ('wiadomość', 'wiadomości')
                         if archivization_counts['too_large'] > 0:
                             description_parts.append(
                                 f'{word_number_form(archivization_counts["too_large"], *forms)} pominięto z '
                                 'powodu zbyt dużego rozmiaru.')
                         if archivization_counts['unknown_error'] > 0:
                             description_parts.append(
                                 f'{word_number_form(archivization_counts["unknown_error"], *forms)} '
                                 'pominięto z powodu niespodziewanych błędów.'
                             )
                         if description_parts:
                             description = '\n'.join(description_parts)
                 except:
                     raise
                 finally:
                     channel_being_processed_for_servers[
                         ctx.guild.id] = None
         embed = self.bot.generate_embed(emoji, notice, description)
         await self.bot.send(ctx, embed=embed)
Esempio n. 17
0
 async def file(self,
                ctx,
                member: Union[discord.Member, int] = None,
                *,
                event_types: Event.comprehend_types = None):
     """Responds with a list of the user's files events on the server."""
     if isinstance(member, int):
         search_by_non_member_id = True
         member_id = member
         try:
             member = await self.bot.fetch_user(member)
         except discord.NotFound:
             member = None
     else:
         search_by_non_member_id = False
         member = member or ctx.author
         member_id = member.id
     with data.session() as session:
         events = session.query(Event)
         if event_types is None:
             events = events.filter(Event.server_id == ctx.guild.id,
                                    Event.user_id == member_id)
         else:
             events = events.filter(Event.server_id == ctx.guild.id,
                                    Event.user_id == member_id,
                                    Event.type.in_(event_types))
         events = events.order_by(Event.occurred_at).all()
         if member == ctx.author:
             address = 'Twoja kartoteka'
         else:
             address = f'Kartoteka {member if member else "usuniętego użytkownika"}'
     if events:
         if event_types is None:
             event_types_description = ''
         elif len(event_types) == 1:
             event_types_description = ' podanego typu'
         elif len(event_types) > 1:
             event_types_description = ' podanych typów'
         event_number_form = word_number_form(len(events), 'zdarzenie',
                                              'zdarzenia', 'zdarzeń')
         embed = self.bot.generate_embed(
             '📂',
             f'{address} zawiera {event_number_form}{event_types_description}',
             'Pokazuję 25 najnowszych.' if len(events) > 25 else '')
         for event in events[-25:]:
             embed.add_field(
                 name=await event.get_presentation(self.bot),
                 value=text_snippet(event.details, Event.MAX_DETAILS_LENGTH)
                 if event.details is not None else '—',
                 inline=False)
     else:
         if search_by_non_member_id:
             embed = self.bot.generate_embed(
                 '⚠️', 'Nie znaleziono na serwerze pasującego użytkownika')
         else:
             notice = 'jest pusta' if event_types is None else 'nie zawiera zdarzeń podanego typu'
             embed = self.bot.generate_embed('📂', f'{address} {notice}')
     await self.bot.send(ctx, embed=embed)
Esempio n. 18
0
 async def on_command_error(self, ctx: commands.Context,
                            error: commands.CommandError):
     with data.session(commit=True) as session:
         invocation = session.query(Invocation).get(ctx.message.id)
         if invocation is not None:
             invocation.exited_at = dt.datetime.now()
             invocation.error = text_snippet(
                 str(error).replace('Command raised an exception: ', ''),
                 Invocation.MAX_ERROR_LENGTH)
Esempio n. 19
0
 async def oof(self, ctx):
     with data.session(commit=True) as session:
         oofer = session.query(Oofer).get({'server_id': ctx.guild.id, 'user_id': ctx.author.id})
         if oofer is not None:
             oofer.oofs = Oofer.oofs + 1
         else:
             oofer = Oofer(server_id=ctx.guild.id, user_id=ctx.author.id)
             session.add(oofer)
     await self.bot.send(ctx, 'Oof!')
Esempio n. 20
0
 async def set(self, ctx, *, new_prefixes_raw: str):
     """Sets a new command prefix."""
     new_prefixes = tuple(
         sorted(filter(None,
                       (prefix.strip()
                        for prefix in new_prefixes_raw.split(' lub '))),
                key=len,
                reverse=True))
     if not new_prefixes:
         raise commands.BadArgument('no valid prefixes')
     new_prefixes_processed = '|'.join(new_prefixes)
     if len(new_prefixes_processed) > data.Server.COMMAND_PREFIX_MAX_LENGTH:
         raise commands.BadArgument('too long')
     self.bot.prefixes[ctx.guild.id] = new_prefixes
     with data.session(commit=True) as session:
         data_server = session.query(data.Server).get(ctx.guild.id)
         previous_prefixes = data_server.command_prefix.split(
             '|') if data_server.command_prefix else ()
         data_server.command_prefix = new_prefixes_processed
     if previous_prefixes:
         previous_prefixes_presentation = ' lub '.join(
             (f'`{prefix}`' for prefix in reversed(previous_prefixes)))
     else:
         previous_prefixes_presentation = f'domyślna `{configuration["command_prefix"]}`'
     if set(previous_prefixes) == set(new_prefixes):
         embed = self.bot.generate_embed(
             'ℹ️',
             f'Nie wprowadzono zmian w {"prefiksie" if len(previous_prefixes) == 1 else "prefiksach"}'
         )
         embed.add_field(
             name='Wartości' if len(previous_prefixes) > 1 else 'Wartość',
             value=' lub '.join(
                 (f'`{prefix}`' for prefix in reversed(previous_prefixes))),
             inline=False)
     else:
         embed = self.bot.generate_embed(
             '✅',
             f'Ustawiono {"prefiks" if len(new_prefixes) == 1 else "prefiksy"}'
         )
         embed.add_field(name='Nowe wartości'
                         if len(new_prefixes) > 1 else 'Nowa wartość',
                         value=' lub '.join(
                             (f'`{prefix}`'
                              for prefix in reversed(new_prefixes))),
                         inline=False)
         embed.add_field(
             name='Poprzednie wartości'
             if len(previous_prefixes) > 1 else 'Poprzednia wartość',
             value=previous_prefixes_presentation,
             inline=False)
     embed.add_field(
         name='Przykłady wywołań',
         value=
         f'`{random.choice(new_prefixes)}wersja` lub `{random.choice(new_prefixes)} oof` '
         f'lub `{ctx.me} urodziny`',
         inline=False)
     await self.bot.send(ctx, embed=embed)
Esempio n. 21
0
 async def on_ready(self):
     with data.session() as session:
         for reminder in session.query(Ballot).filter(
                 Ballot.has_been_concluded == False):
             self.bot.loop.create_task(
                 self.set_off_ballot(reminder.urn_message_id,
                                     reminder.channel_id, reminder.user_id,
                                     reminder.matter, reminder.letters,
                                     reminder.commenced_at,
                                     reminder.conclude_at))
Esempio n. 22
0
 async def on_member_join(self, member: discord.Member):
     """Adds the joining event to the member's file."""
     try:
         with data.session(commit=True) as session:
             event = Event(type='joined',
                           server_id=member.guild.id,
                           user_id=member.id)
             session.add(event)
     except psycopg2.errors.ForeignKeyViolation:
         pass
Esempio n. 23
0
 async def on_member_unban(self, server: discord.Guild, user: discord.User):
     """Adds the unban event to the member's file."""
     try:
         with data.session(commit=True) as session:
             event = Event(type='unbanned',
                           server_id=server.id,
                           user_id=user.id)
             session.add(event)
     except psycopg2.errors.ForeignKeyViolation:
         pass
Esempio n. 24
0
    async def oof_how_many_member(self, ctx, member: discord.Member = None):
        member = member or ctx.author
        with data.session() as session:
            oofer = session.query(Oofer).get({'server_id': ctx.guild.id, 'user_id': member.id})
            oofs = oofer.oofs if oofer is not None else 0

        address = 'Masz' if member == ctx.author else f'{member.display_name} ma'
        embed = self.bot.generate_embed(
            '💨', f'{address} na koncie {word_number_form(oofs, "oofnięcie", "oofnięcia", "oofnięć")}'
        )
        await self.bot.send(ctx, embed=embed)
Esempio n. 25
0
 async def on_command(self, ctx: commands.Context):
     with data.session(commit=True) as session:
         invocation = Invocation(
             message_id=ctx.message.id,
             server_id=ctx.guild.id if ctx.guild is not None else None,
             channel_id=ctx.channel.id,
             user_id=ctx.author.id,
             prefix=ctx.prefix,
             full_command=ctx.command.qualified_name,
             root_command=str(ctx.command.root_parent
                              or ctx.command.qualified_name),
             created_at=utc_to_naive_local(ctx.message.created_at))
         session.add(invocation)
Esempio n. 26
0
 async def info(self, ctx, *, x: str = ''):
     """Responds with current version of the bot."""
     if 'fccchk' in x.lower():
         emoji = '👺'
         notice = f'??? 6.6.6'
         footer = '© 1963 👺'
         server_count = 193
         user_count = 7_802_385_004 + int(
             (dt.datetime.now() - dt.datetime(2020, 1, 1)).total_seconds() *
             2.5)
         mau_count = 1_323_519_222 + int(
             (dt.datetime.now() - dt.datetime(2020, 1, 1)).total_seconds())
         sau_count = 194
         shard_count = 8
         runtime = human_amount_of_time(dt.datetime.now() -
                                        dt.datetime(1963, 11, 22))
         instance_owner = '👺'
         invite_url = 'https:///////////////////////////////'
     else:
         emoji = 'ℹ️'
         notice = f'Somsiad {__version__}'
         footer = __copyright__
         server_count = self.bot.server_count
         user_count = self.bot.user_count
         with data.session() as session:
             thirty_days_ago = dt.datetime.now() - dt.timedelta(30)
             mau_count = (session.query(
                 functions.count(Invocation.user_id.distinct())).filter(
                     Invocation.created_at > thirty_days_ago).scalar())
         shard_count = self.bot.shard_count or 1
         runtime = ('nieznany' if self.bot.ready_datetime is None else
                    human_amount_of_time(dt.datetime.now() -
                                         self.bot.ready_datetime))
         application_info = await self.bot.application_info()
         instance_owner = application_info.owner.mention
         invite_url = self.bot.invite_url()
     embed = self.bot.generate_embed(emoji,
                                     notice,
                                     url=self.bot.WEBSITE_URL)
     embed.add_field(name='Liczba serwerów', value=f'{server_count:n}')
     embed.add_field(name='Liczba użytkowników', value=f'{user_count:n}')
     embed.add_field(name='Liczba aktywnych użytkowników miesięcznie',
                     value=f'{mau_count:n}')
     embed.add_field(name='Liczba shardów', value=f'{shard_count:n}')
     embed.add_field(name='Czas pracy', value=runtime)
     embed.add_field(name='Właściciel instancji', value=instance_owner)
     embed.add_field(name='Link zaproszeniowy bota',
                     value=invite_url,
                     inline=False)
     embed.set_footer(text=footer)
     await self.bot.send(ctx, embed=embed)
Esempio n. 27
0
 async def birthday_where(self, ctx):
     with data.session() as session:
         born_person = session.query(BornPerson).get(ctx.author.id)
         birthday_public_servers_presentation, extra = self._get_birthday_public_servers_presentation(
             born_person,
             on_server_id=ctx.guild.id if ctx.guild else None,
             period=False
         ) if born_person is not None else 'Nie ustawiłeś swojej daty urodzin, więc nie ma czego upubliczniać', None
     embed = discord.Embed(
         title=
         f':information_source: {birthday_public_servers_presentation}',
         description=extra,
         color=self.bot.COLOR)
     await self.bot.send(ctx, embed=embed)
Esempio n. 28
0
 async def vote(
         self,
         ctx,
         conclude_at: Optional[interpret_str_as_datetime] = None,
         *,
         matter: commands.clean_content(fix_channel_mentions=True),
 ):
     if len(matter) > Ballot.MAX_MATTER_LENGTH:
         raise commands.BadArgument
     letters = ''.join(
         {match[0]: None
          for match in self.LETTER_REGEX.findall(matter)})
     if len(letters) < 2:
         letters = None
     description = 'Zagłosuj w tej sprawie przy użyciu reakcji.'
     if conclude_at is not None:
         description += (
             f'\n**Wyniki zostaną ogłoszone {human_datetime(conclude_at)}.**\n*Ogłoszenie wyników zostanie '
             'anulowane jeśli usuniesz tę wiadomość. Możesz to zrobić przy użyciu komendy `nie`.*'
         )
     embed = self.bot.generate_embed('🗳', matter, description)
     urn_message = await self.bot.send(ctx, embed=embed)
     if urn_message is None:
         return
     options = ('👍', '👎') if letters is None else tuple(
         map(self.LETTER_EMOJIS.get, letters))
     try:
         for option in options:
             await urn_message.add_reaction(option)
         details = {
             'urn_message_id': urn_message.id,
             'channel_id': ctx.channel.id,
             'matter': matter,
             'letters': letters,
             'user_id': ctx.author.id,
             'commenced_at': utc_to_naive_local(ctx.message.created_at),
             'conclude_at': conclude_at,
         }
         if conclude_at is not None:
             with data.session(commit=True) as session:
                 reminder = Ballot(**details)
                 session.add(reminder)
                 self.bot.loop.create_task(self.set_off_ballot(**details))
     except discord.Forbidden:
         await urn_message.delete()
         embed = self.bot.generate_embed(
             '⚠️', 'Bot nie ma uprawnień do dodawania reakcji')
     except:
         await urn_message.delete()
         raise
Esempio n. 29
0
 async def birthday_age(self, ctx, *, member: discord.Member = None):
     member = member or ctx.author
     with data.session() as session:
         born_person = session.query(BornPerson).get(member.id)
         if born_person is None or born_person.birthday is None:
             age = None
             is_birthday_unset = True
         else:
             age = born_person.age() if born_person is not None else None
             is_birthday_unset = False
         if is_birthday_unset:
             if member == ctx.author:
                 address = 'Nie ustawiłeś'
             else:
                 address = f'{member} nie ustawił'
             embed = discord.Embed(
                 title=f':question: {address} swojej daty urodzin',
                 description=
                 'Ustawienia można dokonać komendą `urodziny ustaw`.',
                 color=self.bot.COLOR,
             )
         elif not born_person.is_birthday_public(session, ctx.guild):
             if member == ctx.author:
                 address = 'Nie upubliczniłeś'
             else:
                 address = f'{member} nie upublicznił'
             embed = discord.Embed(
                 title=
                 f':question: {address} na tym serwerze swojej daty urodzin',
                 description=
                 'Upublicznienia można dokonać komendą `urodziny upublicznij`.',
                 color=self.bot.COLOR,
             )
         elif age is None:
             address = 'Nie ustawiłeś' if member == ctx.author else f'{member} nie ustawił'
             embed = discord.Embed(
                 title=f':question: {address} swojego roku urodzenia',
                 description=
                 'Ustawienia można dokonać komendą `urodziny ustaw`.',
                 color=self.bot.COLOR,
             )
         else:
             emoji = 'birthday' if born_person.is_birthday_today(
             ) else 'calendar_spiral'
             address = 'Masz' if member == ctx.author else f'{member} ma'
             embed = discord.Embed(
                 title=
                 f':{emoji}: {address} {word_number_form(age, "rok", "lata", "lat")}',
                 color=self.bot.COLOR)
     return await self.bot.send(ctx, embed=embed)
Esempio n. 30
0
 async def birthday_notifications_disable(self, ctx):
     with data.session(commit=True) as session:
         birthday_notifier = session.query(BirthdayNotifier).get(
             ctx.guild.id)
         title = 'ℹ️ Powiadomienia o urodzinach już są wyłączone'
         if birthday_notifier is not None:
             if birthday_notifier.channel_id is not None:
                 birthday_notifier.channel_id = None
                 title = '🔴 Wyłączono powiadomienia o urodzinach'
         else:
             birthday_notifier = BirthdayNotifier(server_id=ctx.guild.id)
             session.add(birthday_notifier)
     embed = discord.Embed(title=title, color=self.bot.COLOR)
     await self.bot.send(ctx, embed=embed)
Esempio n. 31
0
def generate_token(user):
    session = data.session()

    token_id = generate_random_string(40, "".join([
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "0123456789"
    ]))
    token_expiry = int(time()) + CONFIG['token_expiry']

    token = data.Token(token_id, token_expiry, user.id)

    log.debug("Token: %s" % token)

    session.add(token)
    session.commit()

    return token.id
Esempio n. 32
0
def authenticate(user, passwd):
    """Authenticates a user and generates a token
       Returns a token ID when successful, False for password mismatches,
       and None when we can't find the username provided.
    """
    session = data.session()

    # Get user by name. No user match? return None
    users = session.query(data.User).filter_by(username=user)
    if users.count() >= 1:
        user = users.first()
        memberships = session.query(data.RoleMembership).filter_by(user_id=user.id)
        if 'disabled' in [ membership.role.name for membership in memberships ]:
            return False
        else:
            inputhash = hashlib.sha512("".join([passwd, user.salt])).hexdigest()
            if inputhash == user.pwhash:
                return generate_token(user)
            else:
                return False
    else:
        return None