-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrevolt_bridge_platform.py
More file actions
600 lines (498 loc) · 21.2 KB
/
revolt_bridge_platform.py
File metadata and controls
600 lines (498 loc) · 21.2 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
"""
Unifier - A sophisticated Discord bot uniting servers and platforms
Copyright (C) 2024 Green, ItsAsheer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
# Not to be confused with bridge_revolt.py, which manages Revolt client.
# This is a service script to provide essential functions such as
from utils import platform_base
import revolt
import nextcord
from io import BytesIO
from typing import Union, Optional
# from utils.platform_base import ForceRestart
class EmbedField:
def __init__(self, name, value):
self.name = name
self.value = value
class Embed(revolt.SendableEmbed):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields = []
self.raw_description = kwargs.get('description', None)
self.raw_colour = kwargs.get('color', None) or kwargs.get('colour', None)
self.footer = None
@property
def description(self):
if self.fields:
toreturn = (
(self.raw_description + '\n\n') if self.raw_description else ''
) + '\n\n'.join([f'**{field.name}**\n{field.value}' for field in self.fields])
else:
toreturn = self.raw_description
if self.footer:
footer_text = "\n".join([f'##### {line}' for line in self.footer.split('\n')])
toreturn = f'{toreturn}\n\n{footer_text}'
return toreturn
@description.setter
def description(self, value):
self.raw_description = value
@property
def colour(self):
if type(self.raw_colour) is int:
return '#' + hex(self.raw_colour)[2:].zfill(6)
return self.raw_colour
@colour.setter
def colour(self, value):
self.raw_colour = value
def add_field(self, name, value):
self.fields.append(EmbedField(name, value))
def clear_fields(self):
self.fields = []
def insert_field_at(self, index, name, value):
self.fields.insert(index, EmbedField(name, value))
def remove_field(self, index):
self.fields.pop(index)
def set_field_at(self, index, name, value):
self.fields[index] = EmbedField(name, value)
def set_footer(self, text):
self.footer = text
class RevoltPlatform(platform_base.PlatformBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.files_per_guild = True
self.filesize_limit = 20000000
self.supports_agegate = True
def bot_id(self):
return self.bot.user.id
def error_is_unavoidable(self, error):
if type(error) in [revolt.errors.Forbidden, revolt.errors.ServerError]:
return True
elif type(error) is revolt.errors.HTTPError:
# if revolt.py is sane, the above statement should cover all of these errors
# but we'll add this in here just in case it doesn't
try:
if "<html>" in str(error) or "</html>" in str(error):
raise ValueError()
status_code = int(str(error))
except:
# Something probably went exceptionally wrong here, so we'll have to force reboot
try:
# Still pending implementation
# raise ForceRestart()
raise NameError()
except NameError:
# This is probably an older version of Unifier, nothing we can do here
return False
return status_code >= 500 or status_code == 401 or status_code == 403
return False
def get_server(self, server_id):
return self.bot.get_server(server_id)
def get_channel(self, channel_id):
return self.bot.get_channel(channel_id)
def get_user(self, user_id):
return self.bot.get_user(user_id)
def get_member(self, server, user_id):
return server.get_member(user_id)
def channel(self, message: revolt.Message):
return message.channel
def is_nsfw(self, obj):
return obj.nsfw
def server(self, obj):
return obj.server
def content(self, message: revolt.Message):
return message.content
def reply(self, message: revolt.Message):
try:
return message.replies[0]
except:
return message.reply_ids[0]
def roles(self, member):
return member.roles
def get_hex(self, role):
return role.colour.lower().replace('#','',1)
def author(self, message: revolt.Message):
return message.author
def embeds(self, message):
return message.embeds
def attachments(self, message):
return message.attachments
def url(self, message):
return f'https://app.revolt.chat/server/{message.server.id}/channel/{message.channel.id}/{message.id}'
def get_id(self, obj):
return obj.id
def display_name(self, user, message=None):
if message and message.author.id == user.id:
return message.author.masquerade_name or user.display_name or user.name
return user.display_name or user.name
def user_name(self, user, message=None):
if message:
if not message.author.id == user.id:
# mismatch
return None
return message.author.masquerade_name or user.display_name or user.name
return user.name
def name(self, obj):
return obj.name
def avatar(self, user, message=None):
if message:
if not message.author.id == user.id:
# mismatch
return None
return message.author.masquerade_avatar.url if message.author.masquerade_avatar else (
user.avatar.url if user.avatar else None
)
return user.avatar.url if user.avatar else None
def permissions(self, user, channel=None):
if channel:
user_perms = user.get_channel_permissions(channel)
else:
user_perms = user.get_permissions()
permissions = platform_base.Permissions()
permissions.ban_members = user_perms.ban_members
permissions.manage_channels = user_perms.manage_channel
return permissions
def is_bot(self, user):
return user.bot
def attachment_size(self, attachment):
return attachment.size
def attachment_type(self, attachment):
return attachment.content_type
def convert_embeds(self, embeds):
converted = []
for i in range(len(embeds)):
if not type(embeds[i]) is nextcord.Embed:
continue
embed = Embed(
title=embeds[i].title,
description=embeds[i].description,
url=embeds[i].url,
colour=embeds[i].colour.value if embeds[i].colour else None,
icon_url=(
embeds[i].author.icon_url if embeds[i].author else embeds[i].thumbnail.url if embeds[i].thumbnail
else None
)
)
for field in embeds[i].fields:
embed.add_field(field.name, field.value)
if embeds[i].footer:
embed.set_footer(text=embeds[i].footer.text)
if embeds[i].author and not embeds[i].title:
embed.title = embeds[i].author.name
embed.icon_url = embeds[i].author.icon_url
embed.url = embeds[i].author.url
converted.append(embed)
return converted
def convert_embeds_discord(self, embeds):
converted = []
for i in range(len(embeds)):
embed = nextcord.Embed(
title=embeds[i].title,
description=embeds[i].description,
url=embeds[i].url,
# colour=embeds[i].colour.value (do this later)
)
embed.set_thumbnail(url=embeds[i].icon_url)
converted.append(embed)
return converted
def remove_spoilers(self, content):
split_content = content.split('!!')
to_merge = []
# This must be 3 or higher
if len(split_content) >= 3:
to_merge.append(split_content.pop(0))
while len(split_content) > 0:
if len(split_content) >= 2:
split_content.pop(0)
to_merge.append('■■■■■■')
to_merge.append(split_content.pop(0))
return ''.join(to_merge)
else:
return content
async def fetch_server(self, server_id):
return await self.bot.fetch_server(server_id)
async def fetch_channel(self, channel_id):
return await self.bot.fetch_channel(channel_id)
async def fetch_message(self, channel, message_id):
return await channel.fetch_message(message_id)
async def make_friendly(self, text, **kwargs):
# Convert emojis to a URL, if there's only one emoji in the message
if text.startswith(':') and text.endswith(':'):
try:
emoji_id = text.replace(':', '', 1)[:-1]
if len(emoji_id) == 26:
return f'[emoji](https://autumn.revolt.chat/emojis/{emoji_id}?size=48)'
except:
pass
# Convert pings to regular text
components = text.split('<@')
offset = 0
if text.startswith('<@'):
offset = 1
while offset < len(components):
if len(components) == 1 and offset == 0:
break
userid = components[offset].split('>', 1)[0]
try:
user = self.bot.get_user(userid)
display_name = user.display_name
except:
offset += 1
continue
text = text.replace(f'<@{userid}>', f'@{display_name or user.name}').replace(
f'<@!{userid}>', f'@{display_name or user.name}')
offset += 1
# Convert channels to regular text
components = text.split('<#')
offset = 0
if text.startswith('<#'):
offset = 1
while offset < len(components):
if len(components) == 1 and offset == 0:
break
channelid = components[offset].split('>', 1)[0]
try:
try:
channel = self.bot.get_channel(channelid)
except:
channel = await self.bot.fetch_channel(channelid)
if not channel:
raise ValueError()
except:
offset += 1
continue
text = text.replace(f'<#{channelid}>', f'#{channel.name}').replace(
f'<#!{channelid}>', f'#{channel.name}')
offset += 1
# Convert emojis to regular text
components = text.split('<:')
offset = 0
if text.startswith('<:'):
offset = 1
while offset < len(components):
if len(components) == 1 and offset == 0:
break
emojiname = components[offset].split(':', 1)[0]
emojiafter = components[offset].split(':', 1)[1].split('>')[0] + '>'
text = text.replace(f'<:{emojiname}:{emojiafter}', f':{emojiname}\\:')
offset += 1
# Convert animated emojis to regular text
components = text.split('<a:')
offset = 0
if text.startswith('<a:'):
offset = 1
while offset < len(components):
if len(components) == 1 and offset == 0:
break
emojiname = components[offset].split(':', 1)[0]
emojiafter = components[offset].split(':', 1)[1].split('>')[0] + '>'
text = text.replace(f'<a:{emojiname}:{emojiafter}', f':{emojiname}\\:')
offset += 1
# Convert subtext to Revolt format
components = text.split('\n')
newlines = []
for line in components:
if line.startswith('##### ') or line.startswith('###### '):
tags = line.split(' ', 1)[0]
line = line.replace(f'{tags} ', '-# ', 1)
elif line.startswith('#### '):
line = line.replace('#### ', '**', 1) + '**'
newlines.append(line)
text = '\n'.join(newlines)
# Convert spoilers to Discord format
components = text.split('!!')
to_replace = (len(components) - 1) - ((len(components) - 1) % 2)
text = text.replace('!!', '||', to_replace)
return text
async def to_discord_file(self, file):
filebytes = await file.read()
return nextcord.File(fp=BytesIO(filebytes), filename=file.filename, force_close=False)
async def to_platform_file(self, file: Union[nextcord.Attachment, nextcord.File]):
if type(file) is nextcord.Attachment:
f = await file.to_file(use_cached=True)
else:
f = file
return revolt.File(f.fp.read(), filename=f.filename)
def file_name(self, attachment: revolt.Asset):
"""Returns the filename of an attachment."""
return attachment.filename
def file_url(self, attachment: revolt.Asset):
"""Returns the URL of an attachment."""
return attachment.url
async def send(self, channel, content, special: dict = None):
persona = None
bucket_type = None
if hasattr(self, 'buckets'):
bucket_type = platform_base.RateLimit
bucket: Optional[bucket_type] = None
if hasattr(self, 'buckets'):
bucket = self.buckets.get(f'/channels/{channel.id}/messages')
if not bucket:
bucket = platform_base.RateLimit(f'/channels/{channel.id}/messages', 10, 10)
self.buckets.update({f'/channels/{channel.id}/messages': bucket})
def to_color(color):
try:
rgbtuple = tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))
return f'rgb{rgbtuple}'
except:
return None
if 'bridge' in special.keys():
name = special['bridge']['name'] or 'Empty username'
if len(name) > 32:
name = name[:-(len(name)-32)]
if 'emoji' in special['bridge'].keys():
if type(special['bridge']['emoji']) is str:
name = name[:-2] + ' ' + special['bridge']['emoji']
elif 'emoji' in special['bridge'].keys():
if type(special['bridge']['emoji']) is str:
name = name + ' ' + special['bridge']['emoji']
persona = revolt.Masquerade(
name=name,
avatar=special['bridge']['avatar'] if 'avatar' in special['bridge'].keys() else None,
colour=to_color(special['bridge']['color']) if 'color' in special['bridge'].keys() else None
)
try:
me = channel.server.get_member(self.bot.user.id)
except:
me = await channel.server.fetch_member(self.bot.user.id)
if not me.get_permissions().manage_role:
persona.colour = None
# Prevent @everyoneing
content = content.replace("@everyone", "@ everyone")
if not special:
if hasattr(self, 'buckets'):
await self.handle_ratelimit(bucket)
while True:
try:
msg = await channel.send(content)
break
except revolt.errors.HTTPError as e:
if '429' in str(e) and hasattr(self, 'buckets'):
bucket.force_ratelimit()
await self.handle_ratelimit(bucket)
else:
raise
except:
raise
else:
reply_id = None
reply = special.get('reply', None)
source = special.get('source', 'discord')
if reply:
if type(reply) is revolt.Message:
# noinspection PyUnresolvedReferences
reply_id = reply.id
elif type(reply) is str:
reply_id = reply
else:
# probably UnifierMessage, if not then ignore
try:
# noinspection PyUnresolvedReferences
if reply.channel_id == channel.id:
# noinspection PyUnresolvedReferences
reply_id = reply.id
elif reply.source == 'revolt':
# noinspection PyUnresolvedReferences
reply_id = reply.copies[channel.server.id][1]
else:
# noinspection PyUnresolvedReferences
reply_id = reply.external_copies['revolt'][channel.server.id][1]
except:
pass
reply_msg = None
if reply_id:
try:
reply_msg = self.bot.get_message(reply_id)
except:
try:
reply_msg = await channel.fetch_message(reply_id)
except:
pass
if source == 'discord':
newlines = []
for line in content.split('\n'):
if line.startswith('-# '):
line = line.replace('-# ', '##### ', 1)
newlines.append(line)
content = '\n'.join(newlines)
# Convert spoilers to Revolt format
components = content.split('||')
to_replace = (len(components) - 1) - ((len(components) - 1) % 2)
content = content.replace('||', '!!', to_replace)
try:
if hasattr(self, 'buckets'):
await self.handle_ratelimit(bucket)
while True:
try:
msg = await channel.send(
content,
embeds=special['embeds'] if 'embeds' in special.keys() else None,
attachments=special['files'] if 'files' in special.keys() else None,
reply=revolt.MessageReply(reply_msg) if reply_id else None,
masquerade=persona
)
break
except revolt.errors.HTTPError as e:
if '429' in str(e) and hasattr(self, 'buckets'):
bucket.force_ratelimit()
await self.handle_ratelimit(bucket)
else:
raise
except:
raise
except Exception as e:
if str(e) == 'Expected object or value':
if hasattr(self, 'buckets'):
await self.handle_ratelimit(bucket)
while True:
try:
msg = await channel.send(
content,
embeds=special['embeds'] if 'embeds' in special.keys() else None,
reply=revolt.MessageReply(reply_msg) if reply_id else None,
masquerade=persona
)
break
except revolt.errors.HTTPError as e:
if '429' in str(e) and hasattr(self, 'buckets'):
bucket.force_ratelimit()
await self.handle_ratelimit(bucket)
else:
raise
except:
raise
else:
raise
return msg
async def edit(self, message, content, source: str = 'discord', special: dict = None):
if source == 'discord':
newlines = []
for line in content.split('\n'):
if line.startswith('-# '):
line = line.replace('-# ', '##### ', 1)
newlines.append(line)
content = '\n'.join(newlines)
# Convert spoilers to Revolt format
components = content.split('||')
to_replace = (len(components) - 1) - ((len(components) - 1) % 2)
content = content.replace('||', '!!', to_replace)
if not special:
await message.edit(
content=content
)
else:
await message.edit(
content=content,
embeds=special['embeds'] if 'embeds' in special.keys() else None
)
async def delete(self, message):
await message.delete()