This repository has been archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cog.py
262 lines (222 loc) · 9.07 KB
/
cog.py
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import discord
from discord.ext import commands, tasks
import re
import asyncio
from news import CLIENT, PROVIDERS, get_news, news_thread, translate_news
from text import HELP
reUser = re.compile(r"^.+?\.\w+(\/|\/pg\/)(.+?)\/*>?$")
bot_owner_id = 281201917802315776
class NewsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.lock = asyncio.Lock()
self.bulker.start()
# == NEWS UPDATE ==
async def do_bulk(self, provider):
# bulk insert data here
try:
print(provider)
await news_thread(provider, self.bot)
except Exception as e:
print(e)
@tasks.loop(seconds=360.0)
async def bulker(self):
async with self.lock:
for provider in PROVIDERS:
await self.do_bulk(provider)
@bulker.before_loop
async def before_bulker(self):
print('News waiting...')
await self.bot.wait_until_ready()
# == HELP ==
@commands.command(name="help")
async def help(self, ctx):
embed = discord.Embed()
embed.description = HELP.format(prefix=self.bot.command_prefix)
# general info
embed.add_field(name="Author", value=f"<@{bot_owner_id}>\nⱲ0lf#1076")
embed.add_field(name="Library", value="discord.py (Python 🐍)")
embed.add_field(
name="Invite Link",
value=f"[link](https://discordapp.com/oauth2/authorize?client_id={self.bot.user.id}&scope=bot)",
)
embed.add_field(name="Source Code", value="[Github](https://github.com/K0lb3/Rena)")
embed.add_field(name="Sponsor", value="[Github Sponsorship](https://github.com/sponsors/K0lb3)\n[Patreon](https://www.patreon.com/k0lb3)" )
# stats
embed.add_field(
name="Servers", value="{} servers".format(len(self.bot.guilds)))
total_members = sum(len(s.members) for s in self.bot.guilds)
total_online = sum(
1 for m in self.bot.get_all_members() if m.status != discord.Status.offline
)
unique_members = set(map(lambda x: x.id, self.bot.get_all_members()))
embed.add_field(
name="Total Members", value="{} ({} online)".format(total_members, total_online)
)
embed.add_field(name="Unique Members",
value="{}".format(len(unique_members)))
# footnote
embed.set_footer(
text="Made with discord.py", icon_url="http://i.imgur.com/5BFecvA.png"
)
embed.set_thumbnail(url=self.bot.user.avatar_url)
await ctx.send(embed=embed)
@commands.command(name="unsubscribe")
async def unsubscribe(self, ctx):
# check if user is allowed to subscribe
author_perms = ctx.channel.permissions_for(ctx.author)
if not (
author_perms.administrator
or author_perms.manage_messages
or author_perms.manage_webhooks
):
await ctx.send(
"You don't have any of the permissions which are required to use the command.\nThe command can only be used by someone who has at least one of the following permissions in this channel:\nadministrator, managage_messages, manage_webhooks ."
)
# parse input
provider, user_id, src, dst = parse_input(ctx)
if provider == False:
await ctx.send("Invalid host.")
return
if not await self.check_if_correct(ctx, provider, user_id, src, dst):
return
# remove from db
col = CLIENT[provider][user_id]
target = ctx.guild.id, ctx.channel.id
query = {"tl": False} if not dst else {
"tl": True, "src": src, "dst": dst}
cursor = col.find_one(query)
if cursor:
if target_in_cursor(target, cursor["targets"]):
cursor["targets"].remove(list(target))
if len(cursor["targets"]) == 0:
col.delete_one(query)
else:
col.update_one(
query, {"$set": {"targets": cursor["targets"]}})
await ctx.send("Your subscription was removed.")
return
else:
await ctx.send("Couldn't find the subscription.")
else:
await ctx.send("Couldn't find the subscription.")
@commands.command(name="subscribe", alias=["s"])
async def subscribe(self, ctx):
# check if user is allowed to subscribe
author_perms = ctx.channel.permissions_for(ctx.author)
if not (
author_perms.administrator
or author_perms.manage_messages
or author_perms.manage_webhooks
or ctx.author.id == bot_owner_id
):
await ctx.send(
"You don't have any of the permissions which are required to use the command.\nThe command can only be used by someone who has at least one one of the following permissions in this channel:\nadministrator, managage_messages, manage_webhooks ."
)
# check if bot can post in the channel
if not ctx.channel.permissions_for(ctx.me).send_messages:
await ctx.author.send(
f"I'm not allowed to post in **#{ctx.channel.name}**.\nPlease give me the Send Messages permission."
)
return
# parse input
provider, user_id, src, dst = parse_input(ctx)
if provider == False:
await ctx.send("Invalid host.")
return
if not await self.check_if_correct(ctx, provider, user_id, src, dst):
return
# test if the data is valid
try:
news, last_check = await get_news(provider, user_id, 0)
except:
await ctx.send("Invalid input")
return
# add to db
col = CLIENT[provider][user_id]
target = ctx.guild.id, ctx.channel.id
query = {"tl": False} if not dst else {
"tl": True, "src": src, "dst": dst}
cursor = col.find_one(query)
if cursor:
if target_in_cursor(target, cursor["targets"]):
await ctx.send("This setting is already registered for this channel.")
return
cursor["targets"].append(target)
col.update_one(query, {"$set": {"targets": cursor["targets"]}})
# send confirmation message
await ctx.send(
"The subscription was successfully registered.\nYou will receive posts as soon as the selected user posts on their platform."
)
else:
# create entry
col.insert_one({**query, "targets": [target]})
if dst:
news = translate_news(news, src, dst)
for embeds in news:
for embed in embeds:
await ctx.send(embed=embed)
async def check_if_correct(self, ctx, provider, user_id, src, dst):
embed = discord.Embed(description="Is this correct?\nYes - ✅, No - ❌")
embed.add_field(name="Provider", value=provider)
embed.add_field(name="User", value=user_id)
embed.add_field(name="Translation",
value=f"{src} -> {dst}" if dst else "/")
msg = await ctx.send(embed=embed)
try:
await msg.add_reaction("✅")
await msg.add_reaction("❌")
except:
pass
def subscribe_check(reaction, user):
print(user)
if (
reaction.message.id == msg.id
and user.id == ctx.author.id
and reaction.emoji in ["✅", "❌"]
):
return True
return False
try:
reaction, user = await self.bot.wait_for(
"reaction_add", timeout=60.0, check=subscribe_check
)
except asyncio.TimeoutError:
await ctx.send(
"No reaction input of the command caller was detected.\nPlease try again.\n"
)
return False
if reaction.emoji == "❌":
await ctx.send(
f"😖\nI'm sorry if it is my fault.\nIf the detected translation parameter is wrong, please check {self.bot.prefix}help."
)
return False
return True
def parse_input(ctx):
inp = [x.strip(" ")
for x in ctx.message.content.split(" ") if x.strip(" ")][1:]
text = inp[0]
src = "auto"
dst = ""
if len(inp) == 3:
# no translation
src = inp[1]
dst = inp[2]
try:
provider = [x for x in PROVIDERS if x in text][0]
except IndexError:
return False, False, False, False
if provider in ["facebook", "twitter"]:
user_id = reUser.match(text)[2]
elif provider == "famitsu":
user_id = text.rstrip("/").rsplit("/", 1)[1]
elif provider == "steam":
user_id = text[35:].split("/", 1)[0]
return provider, user_id, src, dst
def target_in_cursor(target, targets):
for server, channel in targets:
if server == target[0] and channel == target[1]:
return True
return False
def setup(bot):
bot.add_cog(NewsCog(bot))