-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
310 lines (261 loc) · 11.8 KB
/
bot.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
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
import random
import time
import traceback as tb
from datetime import datetime, timedelta
import discord
import pytz
from discord import Status
from discord.ext import commands
from libs.nhparser import *
from libs.paginator import Paginator
from libs.reddit import *
from libs.util import *
TOKEN = os.getenv("TOKEN")
Musername = os.getenv("MEGAemail")
Mpassword = os.getenv("MEGApassword")
megalogin(Musername, Mpassword)
LOG_CHANNEL = os.getenv("LOG_CHANNEL")
intents = discord.Intents.all() # Not good choice
bot = commands.Bot(command_prefix=commands.when_mentioned_or('`'), intents=intents)
STATUS = Status.online
starting_time = time.time()
localtz = pytz.timezone("Asia/Tehran")
async def send_log(msg):
if LOG_CHANNEL is None:
return
channel = bot.get_channel(int(LOG_CHANNEL))
await channel.send(f'```\n{msg}\n```')
@bot.event
async def on_ready():
global starting_time
starting_time = time.time()
await bot.change_presence(activity=discord.Game(name="Use `help!"))
print(f'{bot.user.name} has connected to Discord!')
await send_log(f'{bot.user.name} Started at {datetime.now(localtz)}')
@bot.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to our Discord server!')
@bot.command(name='echo', help='Repeats a given message', usage="[message...]")
async def echo(ctx, *response):
if not response:
response = ["**I can't send an empty message you fucking idiot**"]
await ctx.send(" ".join(response))
"""rip mashtali 2020-2021 , mashtali is back! :yayy:
"""
@bot.command(name='mashtali', aliases=['shahali'], hidden=True)
async def mashtali(ctx):
await ctx.send("takhte: <https://idroo.com/board-5odTuNxlSF>" + '\n' + "doc: <https://docs.google.com/spreadsheets/d/1rWpFA3IQz7okNZNWhoYKuaHGbp9jVUol37P2WNr2KWc>")
@bot.command(name='vote', help='Starts a vote', usage="<\"question\"> [\"options\"...]")
async def vote(ctx, text, *options):
if not options:
msg = await ctx.send(f"**{ctx.author.display_name}**:\n{text}")
await msg.add_reaction("👍")
await msg.add_reaction("👎")
await msg.add_reaction("🤷")
elif len(options) <= 26:
for i in range(len(options)):
text = text + '\n' + chr(127462 + i) + ": " + options[i]
msg = await ctx.send(f"**{ctx.author.display_name}**:\n{text}")
for i in range(len(options)):
await msg.add_reaction(chr(127462 + i))
else:
return await ctx.send("Too many options!")
await ctx.message.delete()
@bot.command(name='patak', help='Starts a patak vote')
async def patak(ctx , *options):
numbers = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣"]
sakhti = await ctx.send(embed=make_embed("**سختی**"))
for number in numbers:
await sakhti.add_reaction(number)
zibayi = await ctx.send(embed=make_embed("**زیبایی**"))
for number in numbers:
await zibayi.add_reaction(number)
await ctx.message.delete()
@bot.command(name='album', help='posts the most recent pics from the given subreddit \n'
'nsfw is off in sfw channels unless +nsfw is used \n'
'shuffles posts when +random is used \n'
'sends a pdf instead of an album when +pdf is used \n'
'sends a zip instead of an album when +zip is used',
usage="<subreddit> [+nsfw][+random][+pdf][+zip]")
async def album(ctx, sub, *args):
sfw, nsfw = await fetch(sub, "+pdf" in args or "+zip" in args) # pdf ==> no gifs
posts = sfw
if ctx.channel.type is discord.ChannelType.private and "+pdf" not in args and "+zip" not in args:
response = "Sorry, this command is not available in DMs :sob:"
await ctx.send(response)
return
if "+nsfw" in args or (ctx.channel.type is not discord.ChannelType.private and ctx.channel.is_nsfw()):
posts += nsfw
if not posts:
response = "Sorry, couldn't find a pic :sob:"
await ctx.send(response)
return
if "+random" in args:
random.shuffle(posts)
names, links = list(zip(*posts))
if "+zip" in args:
await send_file(ctx, sub, links, 'zip')
elif "+pdf" in args:
await send_file(ctx, sub, links, 'pdf')
else:
paginator = Paginator(bot, ctx, names, links)
await paginator.pagify()
@bot.command(name='nhentai',
help='posts the given sauce \n'
'nsfw is off in sfw channels unless +nsfw is used \n'
'sends a pdf instead of an album when +pdf is used \n'
'sends a zip instead of an album when +zip is used',
usage="<source number> [+nsfw][+pdf][+zip]", hidden=True)
async def nhentai(ctx, sixdigit: int, *args):
posts, name = fetch_hentai(sixdigit)
if ctx.channel.type is discord.ChannelType.private and "+pdf" not in args and "+zip" not in args:
response = "Sorry, this command is not available in DMs :sob:"
await ctx.send(response)
return
if not ("+nsfw" in args or ctx.channel.is_nsfw()):
response = "Sorry, this commnd will only work either when used in a nsfw channel or with +nsfw tag used"
await ctx.send(response)
return
if not posts:
response = "Sorry, couldn't find a Doujin :sob:"
await ctx.send(response)
return
names = [name] * len(posts)
if "+zip" in args:
await send_file(ctx, name, posts, 'zip')
elif "+pdf" in args:
await send_file(ctx, name, posts, 'pdf')
else:
paginator = Paginator(bot, ctx, names, posts)
await paginator.pagify()
@bot.command(name='ping', help="Used to test Montana's response time.")
async def ping(ctx):
start = time.perf_counter()
message = await ctx.send(':ping_pong: Pong!')
end = time.perf_counter()
duration = (end - start) * 1000
await message.edit(content=f'REST API latency: {int(duration)}ms\n'
f'Gateway API latency: {int(bot.latency * 1000)}ms')
@bot.command(name='uptime', help="Prints bot uptime")
async def uptime(ctx):
global starting_time
await ctx.send('Montana has been running for ' + pretty_time_format(time.time() - starting_time))
@bot.command(name="dokme", help="Toggle status", aliases=['lurk'], hidden=True)
@commands.has_role('Admin')
async def dokme(ctx):
global STATUS
if STATUS is Status.invisible:
STATUS = Status.online
await ctx.send(embed=make_embed("I am online now"))
elif STATUS is Status.online:
STATUS = Status.invisible
await ctx.send(embed=make_embed("Pushed dokme successfully"))
await bot.change_presence(status=STATUS, activity=discord.Game(name="Use `help!"))
@bot.command(name="remind", brief="Set a reminder", usage="hh:mm[:ss] <message>")
async def remind(ctx, finish: str, *msg):
"""Set a reminder to echo <message> at given time.
You may mention some role or use +<rolename> in your message"""
hour, minute, *second = list(map(int, finish.split(":")))
second = second[0] if second else 0
if not (0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60) or len(finish.split(':')) > 3:
raise ValueError("Given time is not formatted properly")
content = []
for word in msg:
if len(word) > 1 and word.startswith('+'):
word = (await commands.RoleConverter().convert(ctx, word[1:])).mention
content.append(word)
content = ' '.join(content)
now = datetime.now(localtz)
when = localtz.localize(datetime(year=now.year, month=now.month, day=now.day,
hour=hour, minute=minute, second=second))
if when < now:
return await ctx.send("Time travel?")
await ctx.message.delete()
await ctx.send(embed=make_embed(f"{ctx.author.mention} set a reminder at {finish}, \"{content}\""))
delta = when - now
await asyncio.sleep(delta.total_seconds())
await ctx.send(f"**{ctx.author.mention}**:\n{content}")
@bot.command(name="countdown", brief="Create a countdown", usage="hh:mm[:ss] <message>")
async def countdown(ctx, finish: str, *msg):
hour, minute, *second = list(map(int, finish.split(":")))
second = second[0] if second else 0
if not (0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60) or len(finish.split(':')) > 3:
raise ValueError("Given time is not formatted properly")
delta = timedelta(hours=hour, minutes=minute, seconds=second)
await ctx.message.delete()
msg = await ctx.send("Countdown created!")
while delta:
delta -= timedelta(seconds=1)
h, m, s = map(int, str(delta).split(':'))
await msg.edit(content=f"{h} hours, {m} minutes, {s} seconds remaining")
await asyncio.sleep(0.98)
await msg.edit(content="Time's Up :boom:")
await ctx.send(file=discord.File('static/timeup.gif'))
@bot.command(name='zanbil', brief='Start zanbil detector',
help='Start zanbil detector, write "break" or "zange" to stop')
@commands.has_any_role('teacher', 'Admin')
async def zanbil(ctx, duration: int = 600, penalty: int = 20, channel: discord.VoiceChannel = None):
if channel is None:
# find ctx.author voice channel
if ctx.author.voice is None or ctx.author.voice.channel is None:
return await ctx.send(f'you are not in any vc')
channel = ctx.author.voice.channel
if not duration > 0 < penalty:
raise ValueError('duration and penalty time should be positive')
skeletboard = {}
await ctx.send(f'zanbil detector started at {channel.name}!')
# callback for check breaks
def check_break(msg):
return msg.channel == ctx.channel and \
not msg.author.bot and \
msg.author.voice is not None and msg.author.voice.channel == channel and \
has_any_strrole(msg.author.roles, 'Admin', 'teacher') and \
msg.content in ('break', 'zange', 'siktir')
# sleep for sec and check for break command
async def sleep_for(sec):
try:
await bot.wait_for('message', timeout=sec, check=check_break)
except asyncio.TimeoutError:
return True
return False
while await sleep_for(duration) and filter_bots(channel.members):
# select a member
khardar = random.choice(filter_bots(channel.members))
msg = await ctx.send(f'{khardar.mention}, react \U0001F590 in {penalty} sec or get skelet')
# wait for react
await msg.add_reaction('\U0001F590')
if not await sleep_for(penalty):
break
# check if reacted
msg = await ctx.fetch_message(msg.id)
goodboys = []
for r in msg.reactions:
if r.emoji == '\U0001F590':
goodboys += await r.users().flatten()
if khardar in goodboys:
await msg.add_reaction('\U0001F44C')
else:
await msg.add_reaction('\U0001F9FA')
skeletboard[khardar.mention] = skeletboard.setdefault(khardar.mention, 0) + 1
# output summary
embed = discord.Embed(title='Zanbil Summary')
if skeletboard:
sorted_board = sorted(skeletboard.items(), key=lambda x: -x[1])
embed.description = '\n'.join(f'{m} got {fib(s + 1)} \U0001F480' for m, s in sorted_board)
else:
embed.description = 'no zanbil at all'
await ctx.send(f'zanbil detection is over', embed=embed)
@bot.event
async def on_command_error(ctx, error):
if STATUS is Status.invisible:
return
if isinstance(error, commands.CommandNotFound):
return await ctx.message.add_reaction('\U0001F928')
await ctx.send(embed=make_embed(error))
if LOG_CHANNEL:
trace = tb.format_exception(type(error), error, error.__traceback__)
trace = [line for frame in trace for line in frame.split(r'\n')]
trace = ''.join(trace)
await send_log(trace)
bot.run(TOKEN)