aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--bot/__main__.py1
-rw-r--r--bot/cogs/print_snippets.py45
-rw-r--r--bot/cogs/repo_widgets.py115
3 files changed, 22 insertions, 139 deletions
diff --git a/bot/__main__.py b/bot/__main__.py
index 1d415eb20..3191faf85 100644
--- a/bot/__main__.py
+++ b/bot/__main__.py
@@ -72,7 +72,6 @@ bot.load_extension("bot.cogs.watchchannels")
bot.load_extension("bot.cogs.webhook_remover")
bot.load_extension("bot.cogs.wolfram")
bot.load_extension("bot.cogs.print_snippets")
-bot.load_extension("bot.cogs.repo_widgets")
if constants.HelpChannels.enable:
bot.load_extension("bot.cogs.help_channels")
diff --git a/bot/cogs/print_snippets.py b/bot/cogs/print_snippets.py
index 67d411a63..3f784d2c6 100644
--- a/bot/cogs/print_snippets.py
+++ b/bot/cogs/print_snippets.py
@@ -1,9 +1,10 @@
+import asyncio
import os
import re
import textwrap
import aiohttp
-from discord import Message
+from discord import Message, Reaction, User
from discord.ext.commands import Cog
from bot.bot import Bot
@@ -113,8 +114,8 @@ class PrintSnippets(Cog):
headers['Authorization'] = f'token {os.environ["GITHUB_TOKEN"]}'
file_contents = await fetch_http(
self.session,
- f'https://api.github.com/repos/{d["repo"]}\
- /contents/{d["file_path"]}?ref={d["branch"]}',
+ f'https://api.github.com/repos/{d["repo"]}'
+ + f'/contents/{d["file_path"]}?ref={d["branch"]}',
'text',
headers=headers,
)
@@ -124,8 +125,8 @@ class PrintSnippets(Cog):
d = gh_gist.groupdict()
gist_json = await fetch_http(
self.session,
- f'https://api.github.com/gists/{d["gist_id"]}\
- {"/" + d["revision"] if len(d["revision"]) > 0 else ""}',
+ f'https://api.github.com/gists/{d["gist_id"]}'
+ + f'{"/" + d["revision"] if len(d["revision"]) > 0 else ""}',
'json',
)
for f in gist_json['files']:
@@ -147,8 +148,8 @@ class PrintSnippets(Cog):
headers['PRIVATE-TOKEN'] = os.environ["GITLAB_TOKEN"]
file_contents = await fetch_http(
self.session,
- f'https://gitlab.com/api/v4/projects/{d["repo"]}/\
- repository/files/{d["file_path"]}/raw?ref={d["branch"]}',
+ f'https://gitlab.com/api/v4/projects/{d["repo"]}/'
+ + f'repository/files/{d["file_path"]}/raw?ref={d["branch"]}',
'text',
headers=headers,
)
@@ -168,22 +169,20 @@ class PrintSnippets(Cog):
message_to_send = message_to_send[:-1]
- if len(message_to_send) > 2000:
- await message.channel.send(
- 'Sorry, Discord has a 2000 character limit. Please send a shorter '
- + 'snippet or split the big snippet up into several smaller ones :slight_smile:'
- )
- elif len(message_to_send) == 0:
- await message.channel.send(
- 'Please send valid snippet links to prevent spam :slight_smile:'
- )
- elif message_to_send.count('\n') > 50:
- await message.channel.send(
- 'Please limit the total number of lines to at most 50 to prevent spam :slight_smile:'
- )
- else:
- await message.channel.send(message_to_send)
- await message.edit(suppress=True)
+ if 0 < len(message_to_send) <= 2000 and message_to_send.count('\n') <= 50:
+ sent_message = await message.channel.send(message_to_send)
+ await message.edit(suppress=True)
+ await sent_message.add_reaction('❌')
+
+ def check(reaction: Reaction, user: User) -> bool:
+ return user == message.author and str(reaction.emoji) == '❌'
+
+ try:
+ reaction, user = await self.bot.wait_for('reaction_add', timeout=10.0, check=check)
+ except asyncio.TimeoutError:
+ await sent_message.remove_reaction('❌', self.bot.user)
+ else:
+ await sent_message.delete()
def setup(bot: Bot) -> None:
diff --git a/bot/cogs/repo_widgets.py b/bot/cogs/repo_widgets.py
deleted file mode 100644
index 32c2451df..000000000
--- a/bot/cogs/repo_widgets.py
+++ /dev/null
@@ -1,115 +0,0 @@
-import os
-import re
-
-import aiohttp
-from discord import Embed, Message
-from discord.ext.commands import Cog
-
-from bot.bot import Bot
-
-
-async def fetch_http(session: aiohttp.ClientSession, url: str, response_format: str, **kwargs) -> str:
- """Uses aiohttp to make http GET requests."""
- async with session.get(url, **kwargs) as response:
- if response_format == 'text':
- return await response.text()
- elif response_format == 'json':
- return await response.json()
-
-
-async def orig_to_encode(d: dict) -> dict:
- """Encode URL Parameters."""
- for obj in d:
- if d[obj] is not None:
- d[obj] = d[obj].replace('/', '%2F').replace('.', '%2E')
-
-
-GITHUB_RE = re.compile(
- r'https://github\.com/(?P<owner>[^/]+?)/(?P<repo>[^/]+?)(?:\s|$)')
-
-GITLAB_RE = re.compile(
- r'https://gitlab\.com/(?P<owner>[^/]+?)/(?P<repo>[^/]+?)(?:\s|$)')
-
-
-class RepoWidgets(Cog):
- """
- Cog that sends pretty embeds of repos.
-
- Matches each message against a regex and sends an embed with the details of all referenced repos.
- """
-
- def __init__(self, bot: Bot):
- """Initializes the cog's bot."""
- self.bot = bot
- self.session = aiohttp.ClientSession()
-
- @Cog.listener()
- async def on_message(self, message: Message) -> None:
- """Checks if the message has a repo link, removes the embed, then sends a rich embed."""
- gh_match = GITHUB_RE.search(message.content)
- gl_match = GITLAB_RE.search(message.content)
-
- if (gh_match or gl_match) and not message.author.bot:
- for gh in GITHUB_RE.finditer(message.content):
- d = gh.groupdict()
- headers = {}
- if 'GITHUB_TOKEN' in os.environ:
- headers['Authorization'] = f'token {os.environ["GITHUB_TOKEN"]}'
- repo = await fetch_http(
- self.session,
- f'https://api.github.com/repos/{d["owner"]}/{d["repo"]}',
- 'json',
- headers=headers,
- )
-
- embed = Embed(
- title=repo['full_name'],
- description='No description provided' if repo[
- 'description'] is None else repo['description'],
- url=repo['html_url'],
- color=0x111111
- ).set_footer(
- text=f'Language: {repo["language"]} | '
- + f'Stars: {repo["stargazers_count"]} | '
- + f'Forks: {repo["forks_count"]} | '
- + f'Size: {repo["size"]}kb'
- ).set_thumbnail(url=repo['owner']['avatar_url'])
- if repo['homepage']:
- embed.add_field(name='Website', value=repo['homepage'])
- await message.channel.send(embed=embed)
-
- for gl in GITLAB_RE.finditer(message.content):
- d = gl.groupdict()
- await orig_to_encode(d)
- headers = {}
- if 'GITLAB_TOKEN' in os.environ:
- headers['PRIVATE-TOKEN'] = os.environ["GITLAB_TOKEN"]
- repo = await fetch_http(
- self.session,
- f'https://gitlab.com/api/v4/projects/{d["owner"]}%2F{d["repo"]}',
- 'json',
- headers=headers,
- )
-
- embed = Embed(
- title=repo['path_with_namespace'],
- description='No description provided' if repo[
- 'description'] == "" else repo['description'],
- url=repo['web_url'],
- color=0x111111
- ).set_footer(
- text=f'Stars: {repo["star_count"]} | '
- + f'Forks: {repo["forks_count"]}'
- )
-
- if repo['avatar_url'] is not None:
- embed.set_thumbnail(url=repo['avatar_url'])
-
- await message.channel.send(embed=embed)
-
- await message.edit(suppress=True)
-
-
-def setup(bot: Bot) -> None:
- """Load the Utils cog."""
- bot.add_cog(RepoWidgets(bot))