Esempio n. 1
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. 2
0
 async def isitup(self, ctx, *, query='https://google.com'):
     """Returns information about website status."""
     async with ctx.typing():
         protocol, rest = first_url(query, protocol_separate=True)
         url_valid = rest is not None and protocol in (None, 'http', 'https')
         status = None
         if url_valid:
             protocol = protocol or 'https'
             url = f'{protocol}://{rest}'
             try:
                 for method in (self.bot.session.head, self.bot.session.get):
                     async with method(url, allow_redirects=True) as request:
                         if request.status == 405 and request.method != 'get':
                             continue
                         status = request.status
             except aiohttp.InvalidURL:
                 url_valid = False
             except aiohttp.ClientConnectorError:
                 pass
         if url_valid:
             if status is not None and status // 100 == 2:
                 emoji, notice = '✅', f'Strona {rest} jest dostępna'
             else:
                 emoji, notice = '🔴', f'Strona {rest} nie jest dostępna'
             if status is not None:
                 status_presentation = md_link(status, self.HTTP_CODE_WIKIPEDIA_URLS[status // 100])
             else:
                 status_presentation = 'brak odpowiedzi'
             embed = self.bot.generate_embed(emoji, notice, url=url)
             embed.add_field(name='Status', value=status_presentation)
         else:
             embed = self.bot.generate_embed('⚠️', 'Podany adres jest niepoprawny')
         await self.bot.send(ctx, embed=embed)
Esempio n. 3
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. 4
0
 async def set_off_burning(
     self,
     confirmation_message_id: int,
     target_message_id: int,
     channel_id: int,
     user_id: int,
     requested_at: dt.datetime,
     execute_at: dt.datetime,
 ):
     if confirmation_message_id in self.burnings_set_off:
         return
     self.burnings_set_off.add(confirmation_message_id)
     await discord.utils.sleep_until(execute_at.astimezone())
     if confirmation_message_id not in self.burnings_set_off:
         return
     self.burnings_set_off.remove(confirmation_message_id)
     channel = self.bot.get_channel(channel_id)
     try:
         target_message = await channel.fetch_message(target_message_id)
         confirmation_message = await channel.fetch_message(
             confirmation_message_id)
     except (AttributeError, discord.NotFound):
         pass
     else:
         try:
             await target_message.delete()
         except discord.NotFound:
             pass
         else:
             burning_description = md_link(
                 f'Usunięto twoją wiadomość wysłaną {human_datetime(requested_at)}.',
                 confirmation_message.jump_url)
             burning_embed = self.bot.generate_embed(
                 '✅', 'Spalono wiadomość', burning_description)
             burning_message = await channel.send(f'<@{user_id}>',
                                                  embed=burning_embed)
             confirmation_description = md_link(
                 f'Usunięto twoją wiadomość {human_datetime()}.',
                 burning_message.jump_url)
             confirmation_embed = self.bot.generate_embed(
                 '✅', 'Spalono wiadomość', confirmation_description)
             await confirmation_message.edit(embed=confirmation_embed)
     with data.session(commit=True) as session:
         reminder = session.query(Burning).get(confirmation_message_id)
         reminder.has_been_executed = True
Esempio n. 5
0
 def _embed_personal_stats(self):
     if self.total_message_count:
         earliest = self.earliest_relevant_message
         latest = self.latest_relevant_message
         self.embed.add_field(
             name=f'Wysłał pierwszą wiadomość na serwerze {"w przedziale czasowym" if self.last_days else ""}',
             value=md_link(
                 human_datetime(earliest.datetime),
                 f'https://discordapp.com/channels/{earliest.server_id}/{earliest.channel_id}/{earliest.id}'
             ),
             inline=False
         )
         if self.ctx.author != self.subject:
             self.embed.add_field(
                 name='Wysłał ostatnią wiadomość na serwerze',
                 value=md_link(
                     human_datetime(latest.datetime),
                     f'https://discordapp.com/channels/{latest.server_id}/{latest.channel_id}/{latest.id}'
                 ),
                 inline=False
             )
     self._embed_general_message_stats()
     self._embed_top_visible_channel_stats()
Esempio n. 6
0
 def _generate_category_embed(self):
     """Analyzes the subject as a category."""
     self.embed = self.ctx.bot.generate_embed(
         '📈', f'Przygotowano raport o kategorii {self.subject}', self.description
     )
     self.embed.add_field(name='Utworzono', value=human_datetime(self.subject.created_at, utc=True), inline=False)
     if self.total_message_count:
         earliest = self.earliest_relevant_message
         self.embed.add_field(
             name=f'Wysłano pierwszą wiadomość {"w przedziale czasowym" if self.last_days else ""}',
             value=md_link(
                 human_datetime(earliest.datetime),
                 f'https://discordapp.com/channels/{earliest.server_id}/{earliest.channel_id}/{earliest.id}'
             ),
             inline=False
         )
     self.embed.add_field(name='Kanałów tekstowych', value=f'{len(self.subject.text_channels):n}')
     self.embed.add_field(name='Kanałów głosowych', value=f'{len(self.subject.voice_channels):n}')
     self._embed_general_message_stats()
     self._embed_top_visible_channel_stats()
     self._embed_top_active_user_stats()
Esempio n. 7
0
 async def robot9000(self,
                     ctx: commands.Context,
                     sent_by: discord.Member = None):
     """Finds previous occurences of the image being sent."""
     with ctx.typing():
         attachment, _ = await self.find_image(
             ctx.channel,
             sent_by=sent_by,
             message_id=ctx.message.reference.message_id
             if ctx.message is not None
             and ctx.message.reference is not None else None,
         )
         if attachment is not None:
             with data.session() as session:
                 similar = []
                 base_image9000 = session.query(Image9000).get(
                     attachment.id)
                 if base_image9000 is None:
                     embed = self.bot.generate_embed(
                         '⚠️', 'Nie znaleziono obrazka do sprawdzenia')
                 else:
                     init_time = time.time()
                     comparison_count = 0
                     sent_by = ctx.guild.get_member(base_image9000.user_id)
                     for other_image9000 in session.query(Image9000).filter(
                             Image9000.server_id == ctx.guild.id,
                             Image9000.attachment_id != attachment.id):
                         comparison_count += 1
                         similarity = base_image9000.calculate_similarity_to(
                             other_image9000)
                         if similarity >= self.IMAGE9000_SIMILARITY_TRESHOLD:
                             similar.append((other_image9000, similarity))
                     if similar:
                         embed = self.bot.generate_embed()
                         for image9000, similarity in similar:
                             channel = image9000.discord_channel(self.bot)
                             message = None
                             info = ''
                             if channel is not None:
                                 try:
                                     message = await channel.fetch_message(
                                         image9000.message_id)
                                 except discord.NotFound:
                                     info = ' (wiadomość usunięta)'
                             else:
                                 info = ' (kanał usunięty)'
                             similarity_presentantion = f'{int(round(similarity*100))}% podobieństwa'
                             embed.add_field(
                                 name=await
                                 image9000.get_presentation(self.bot),
                                 value=md_link(
                                     similarity_presentantion,
                                     message.jump_url if message is not None
                                     else None) + info,
                                 inline=False,
                             )
                         occurences_form = word_number_form(
                             len(embed.fields),
                             'wcześniejsze wystąpienie',
                             'wcześniejsze wystąpienia',
                             'wcześniejszych wystąpień',
                         )
                         embed.title = (
                             f'🤖 Wykryłem {occurences_form} na serwerze obrazka wysłanego przez {sent_by} o '
                             f'{base_image9000.sent_at.strftime("%-H:%M")}')
                     else:
                         embed = self.bot.generate_embed(
                             '🤖',
                             f'Nie wykryłem, aby obrazek wysłany przez {sent_by} '
                             f'o {base_image9000.sent_at.strftime("%-H:%M")} wystąpił wcześniej na serwerze',
                         )
                     comparison_time = time.time() - init_time
                     seen_image_form = word_number_form(
                         comparison_count, 'obrazek zobaczony',
                         'obrazki zobaczone', 'obrazków zobaczonych')
                     embed.set_footer(
                         text=
                         f'Przejrzano {seen_image_form} do tej pory na serwerze w {round(comparison_time, 2):n} s.'
                     )
         else:
             embed = self.bot.generate_embed(
                 '⚠️', 'Nie znaleziono obrazka do sprawdzenia')
         await self.bot.send(ctx, embed=embed)
Esempio n. 8
0
 async def set_off_ballot(
     self,
     urn_message_id: int,
     channel_id: int,
     user_id: int,
     matter: str,
     letters: Optional[str],
     commenced_at: dt.datetime,
     conclude_at: dt.datetime,
 ):
     if urn_message_id in self.ballots_set_off:
         return
     self.ballots_set_off.add(urn_message_id)
     await discord.utils.sleep_until(conclude_at.astimezone())
     if urn_message_id not in self.ballots_set_off:
         return
     self.ballots_set_off.remove(urn_message_id)
     channel = self.bot.get_channel(channel_id)
     try:
         urn_message = await channel.fetch_message(urn_message_id)
     except (AttributeError, discord.NotFound):
         pass
     else:
         emojis = ('👍', '👎') if letters is None else tuple(
             map(self.LETTER_EMOJIS.get, letters))
         results = {
             reaction.emoji: reaction.count - 1
             for reaction in urn_message.reactions
             if reaction.emoji in emojis
         }
         winning_emojis = []
         winning_count = -1
         for option in results.items():
             if option[1] > winning_count:
                 winning_emojis = [option[0]]
                 winning_count = option[1]
             elif option[1] == winning_count:
                 winning_emojis.append(option[0])
         winning_emoji = '❓' if len(
             winning_emojis) != 1 else winning_emojis[0]
         results_description = md_link(
             f'Wyniki głosowania ogłoszonego {human_datetime(commenced_at)}.',
             urn_message.jump_url)
         urn_embed = self.bot.generate_embed(winning_emoji, matter)
         results_embed = self.bot.generate_embed(winning_emoji, matter,
                                                 results_description)
         positions = ('Za', 'Przeciw') if letters is None else (
             f'Opcja {letter}' for letter in letters)
         total_count = sum(
             results.values()) or 1  # guard against zero-division
         for position, emoji in zip(positions, emojis):
             this_count = results.get(emoji)
             if this_count is None:
                 continue
             this_percentage = this_count / total_count * 100
             count_presentation = f'{this_count:n} ({round(this_percentage):n}%)'
             if emoji in winning_emojis and winning_count > 0:
                 count_presentation = f'**{count_presentation}**'
             urn_embed.add_field(name=position, value=count_presentation)
             results_embed.add_field(name=position,
                                     value=count_presentation)
         results_message = await channel.send(f'<@{user_id}>',
                                              embed=results_embed)
         urn_embed.description = md_link(
             f'Głosowanie zostało zakończone {human_datetime()}.',
             results_message.jump_url)
         await urn_message.edit(embed=urn_embed)
     with data.session(commit=True) as session:
         reminder = session.query(Ballot).get(urn_message_id)
         reminder.has_been_concluded = True