This repository was archived by the owner on Jan 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLatestBotController.py
More file actions
100 lines (86 loc) · 4.16 KB
/
LatestBotController.py
File metadata and controls
100 lines (86 loc) · 4.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import asyncio
import re
import asyncpraw
from asyncpraw import exceptions as rexc
from discord.ext import commands as cmd
from cfg import settings # see note in README.md
bot = cmd.Bot(help_command=None) # create discord instance
reddit_agent = asyncpraw.Reddit(
client_id=settings['redditAPI']['client_id'],
client_secret=settings['redditAPI']['client_secret'],
user_agent=settings['redditAPI']['user_agent']
) # creates single (shared) read-only reddit instance
async def shutdown():
# safe log-out from reddit && discord
await reddit_agent.close()
await bot.close()
@bot.event
async def on_ready():
print(f'@ Boot successful. Logged as {bot.user}, slash command mode')
# tells host if bot is ready to use
print(f'@ Permissions: Reddit.read_only={reddit_agent.read_only}')
# tells if bot has permissions to read/write comments && posts
@bot.slash_command(name='about', description='General bot information')
async def _about(context):
await context.respond(f'Open source Discord bot used for extracting '
f'content from reddit posts.\n'
f'Project page on Github: '
f'<https://github.com/HardcoreMagazine/RedditToDiscordShare>')
@bot.slash_command(name='exi', description='Extract image/links from selected post')
async def _exi(context, url):
typesafe_url = url.replace("<", "").replace(">", "").replace("|", "")
try:
await context.defer() # wait for reddit API response
submission = await reddit_agent.submission(url=typesafe_url)
# request all data from selected post
embedded_link = submission.url
await context.respond(embedded_link)
except Exception as exc:
if isinstance(exc, rexc.InvalidURL):
await context.respond('Invalid reddit URL')
elif isinstance(exc, rexc.RedditAPIException):
await context.respond('Reddit API error, try again later')
else:
print(f'@ An exception has occurred: "{exc}"')
@bot.slash_command(name='ext', description='Extract text from selected post')
async def _ext(context, url):
typesafe_url = url.replace("<", "").replace(">", "").replace("|", "")
try:
await context.defer() # wait for reddit API response
submission = await reddit_agent.submission(url=typesafe_url)
# request all data from selected post
s_title = submission.title
s_text: str = submission.selftext
max_text_size = 2000
if len(s_text) > max_text_size:
await context.respond(f'Submission contains more than {max_text_size} '
f'characters, unable to process '
f'due to Discord limitations')
else:
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)" \
r"(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))" \
r"+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)" \
r"|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
link_list = re.findall(regex, s_text)
if link_list: # if list is not empty
for link in link_list:
conv_link = ''.join(link)
s_text = s_text.replace(conv_link, f"<{conv_link}>")
# hide all included links ("HTTP(S)://") in <> brackets
s_text = s_text.replace("​", '')
# "​" - zero-width space character
# pops up occasionally due to random
# errors on reddit side
await context.respond(f'> {s_title}\n\n'
f'' # escape discord quote
f'{s_text}')
except Exception as exc:
if isinstance(exc, rexc.InvalidURL):
await context.respond('Invalid URL')
elif isinstance(exc, rexc.RedditAPIException):
await context.respond('Reddit API is down, try again later')
print(f'@ An exception has occurred: "{exc}"')
bot.run(settings['discordAPI']['token']) # creates discord bot instance
# code below this line executes on program shutdown
print('@ Shutdown in progress')
asyncio.run(shutdown())