-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFun.py
323 lines (293 loc) · 12 KB
/
Fun.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
311
312
313
314
315
316
317
318
319
320
321
322
323
import discord, random, base64, aiohttp, cat, hashlib, json, akinator, datetime, urllib, math, requests, asyncio, re, secrets, urllib, time, sys, importlib, os
from akimenu import channel_is_nsfw, get_menu
from akinator.async_aki import Akinator
from discord import ext
import humanize as h
from random import choice
from io import BytesIO
from utils.tools import *
from utils.unicode import *
from utils.fun.lists import *
from PIL import Image
from utils.fun.fortunes import fortunes
from utils import imagetools, checks, config
from utils.language import Language
from discord.ext import commands
from discord.ext.commands import Bot, has_permissions, MissingPermissions
from utils import lists, permissions, http, default, argparser, dataIO
coinsides = ["Heads", "Tails"]
punlist = open("Punlist.txt", encoding="utf8").read().splitlines()
def setup(bot):
bot.add_cog(Fun(bot))
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession()
@commands.command()
@commands.guild_only()
async def pun(self, ctx):
"""Grab a EGG-celent pun..."""
await ctx.send(random.choice(punlist))
@commands.command(aliases=["quoteoftheday", "inspireme"])
@commands.guild_only()
async def qotd(self, ctx):
"""Quotes to get you through the day"""
Quotes = open("Quotes.txt", encoding="utf8").read().splitlines()
await ctx.send(random.choice(Quotes))
@commands.command()
@commands.guild_only()
async def rps(self, ctx, choice: str):
"""Play rock-paper-scissors"""
try:
userChoice = choice.lower()
if (
userChoice != "rock"
and userChoice != "paper"
and userChoice != "scissors"
):
await ctx.send("You can only choose from rock, paper or scissors")
else:
temp = random.randint(1, 3)
if temp == 1:
botChoice = "rock"
elif temp == 2:
botChoice = "paper"
elif temp == 3:
botChoice = "scissors"
# This is kind of ugly but it works
if userChoice == botChoice:
await ctx.send(
"I choose **{}**. The game was a tie!".format(botChoice)
)
elif userChoice == "rock":
if botChoice == "paper":
await ctx.send("I choose **{}**. I win!".format(botChoice))
elif botChoice == "scissors":
await ctx.send("I choose **{}**. You win!".format(botChoice))
elif userChoice == "paper":
if botChoice == "scissors":
await ctx.send("I choose **{}**. I win!".format(botChoice))
elif botChoice == "rock":
await ctx.send("I choose **{}**. You win!".format(botChoice))
elif userChoice == "scissors":
if botChoice == "rock":
await ctx.send("I choose **{}**. I win!".format(botChoice))
elif botChoice == "paper":
await ctx.send("I choose **{}**. You win!".format(botChoice))
except Exception as e:
await ctx.send(e)
@commands.max_concurrency(1, commands.BucketType.channel)
@commands.guild_only()
@commands.bot_has_permissions(embed_links=True, add_reactions=True)
@commands.has_permissions(embed_links=True, add_reactions=True)
@commands.command(aliases=["akinator"])
async def aki(
self,
ctx: commands.Context,
language: str.lower = "en",
use_buttons: bool = True,
):
"""
Start a game of Akinator!
Controls:
> ✅ : yes
> ❎ : no
> ❔ : i don't know
> 📉 : probably
> 📈 : probably not
> 🔙 : back
> 🏆 : win
> 🗑️ : cancel
"""
await ctx.trigger_typing()
aki = Akinator()
child_mode = not channel_is_nsfw(ctx.channel)
try:
await aki.start_game(
language=language.replace(" ", "_"),
child_mode=child_mode,
client_session=self.session,
)
except akinator.InvalidLanguageError:
await ctx.send(
"Invalid language. Refer here to view valid languages.\n<https://github.com/NinjaSnail1080/akinator.py#functions>"
)
except Exception:
await ctx.send(
"I encountered an error while connecting to the Akinator servers."
)
else:
aki_color = discord.Color(0xE8BC90)
menu = get_menu(buttons=use_buttons)
await menu(aki, aki_color).start(ctx)
@commands.command(brief="Generates a random password string for you")
@commands.guild_only()
async def password(self, ctx, nbytes: int = 18):
if nbytes not in range(3, 1401):
return await ctx.send("I only accept any numbers between 3-1400")
if hasattr(ctx, "guild") and ctx.guild is not None:
await ctx.send(
f"Sending you a private message with your random generated password **{ctx.author.name}**"
)
await ctx.author.send(
f"🎁 **Here is your password:**\n{secrets.token_urlsafe(nbytes)}"
)
@commands.command()
@commands.guild_only()
async def insult(self, ctx, member: discord.Member):
"""Says something mean about you."""
await ctx.send(member.mention + " " + random.choice(config.insults))
@commands.command()
@commands.guild_only()
async def coinflip(self, ctx):
"""Flip a Frikin Coin"""
await ctx.send(random.choice(coinsides))
@commands.command(hidden=True, aliases=["changeavatar", "newavatar"])
@commands.cooldown(1, 654, commands.BucketType.guild)
@commands.is_owner()
@commands.guild_only()
async def change_avatar(self, ctx, url: str = None):
"""Change avatar."""
if url is None and len(ctx.message.attachments) == 1:
url = ctx.message.attachments[0].url
else:
url = url.strip("<>") if url else None
try:
bio = await http.get(url, res_method="read")
await self.bot.user.edit(avatar=bio)
await ctx.send(f"Successfully changed the avatar. Currently using:\n{url}")
except aiohttp.InvalidURL:
await ctx.send("The URL is invalid...")
except discord.InvalidArgument:
await ctx.send("This URL does not contain a useable image")
except discord.HTTPException as err:
await ctx.send(err)
except TypeError:
await ctx.send(
"You need to either provide an image URL or upload one with the command"
)
@commands.command(aliases=["directmessage", "pm"])
@commands.guild_only()
@commands.cooldown(1, 35, commands.BucketType.user)
async def dm(self, ctx, member: discord.Member, *, message: str):
"""DM the user of your choice"""
role = discord.utils.find(lambda r: r.name == "nodm", ctx.guild.roles)
user = member
if not user:
return await ctx.send(f"Could not find any UserID matching **{user_id}**")
try:
# if not role in user.roles:
if role in user.roles:
return await ctx.send(
"This user has the no dm role. This means they probably don't want DMs."
)
await ctx.send(f"✉️ Sent a DM to **{member.name}**")
await user.send(message)
await user.send(f"Message sent by: {ctx.author}")
except discord.Forbidden:
await ctx.send(
"This user might be having DMs blocked or it's a bot account..."
)
@commands.command(aliases=["mcprofile", "mcinfo"])
@commands.guild_only()
async def minecraft(self, ctx, username):
"""
Shows MC account info, skin and username history
"""
try:
uuid = requests.get(
"https://api.mojang.com/users/profiles/minecraft/{}".format(username)
).json()["id"]
url = json.loads(
base64.b64decode(
requests.get(
"https://sessionserver.mojang.com/session/minecraft/profile/{}".format(
uuid
)
).json()["properties"][0]["value"]
).decode("utf-8")
)["textures"]["SKIN"]["url"]
names = requests.get(
"https://api.mojang.com/user/profiles/{}/names".format(uuid)
).json()
history = "**Name History:**\n"
for name in reversed(names):
history += name["name"] + "\n"
await ctx.send(
"**Username: `{}`**\n**Skin: {}**\n**UUID: {}**".format(
username, url, uuid
)
)
await ctx.send(history)
except ValueError as e:
await ctx.send(e)
await asyncio.sleep(2)
await ctx.send("This means the profile wasn't found...")
@commands.command(aliases=["wiki"])
@commands.is_nsfw()
@commands.guild_only()
async def wikipedia(self, ctx, *, query: str):
"""
Uses Wikipedia APIs to summarise search
"""
sea = requests.get(
(
"https://en.wikipedia.org//w/api.php?action=query"
"&format=json&list=search&utf8=1&srsearch={}&srlimit=5&srprop="
).format(query)
).json()["query"]
if sea["searchinfo"]["totalhits"] == 0:
await ctx.send("Sorry, your search could not be found.")
else:
for x in range(len(sea["search"])):
article = sea["search"][x]["title"]
req = requests.get(
"https://en.wikipedia.org//w/api.php?action=query"
"&utf8=1&redirects&format=json&prop=info|images"
"&inprop=url&titles={}".format(article)
).json()["query"]["pages"]
if str(list(req)[0]) != "-1":
break
else:
await ctx.send("Sorry, your search could not be found.")
return
article = req[list(req)[0]]["title"]
arturl = req[list(req)[0]]["fullurl"]
artdesc = requests.get(
"https://en.wikipedia.org/api/rest_v1/page/summary/" + article
).json()["extract"]
lastedited = datetime.datetime.strptime(
req[list(req)[0]]["touched"], "%Y-%m-%dT%H:%M:%SZ"
)
embed = discord.Embed(
title="**" + article + "**",
url=arturl,
description=artdesc,
color=0x3FCAFF,
)
embed.set_footer(
text="Wiki entry last modified",
icon_url="https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png",
)
embed.set_author(
name="Wikipedia",
url="https://en.wikipedia.org/",
icon_url="https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png",
)
embed.timestamp = lastedited
await ctx.send(
'**Search result for:** ***"{}"***:'.format(query), embed=embed
)
@commands.command()
@commands.guild_only()
async def cat(self, ctx):
"""Like the shibe command, but with cats."""
cats = open("cats.txt").read().splitlines()
cat2 = random.choice(cats)
await ctx.send(cat2)
@commands.command(description="What time is it?")
@commands.guild_only()
async def clock(self, ctx):
now = datetime.datetime.now()
current_time = now.strftime("%H:%M:%S")
await ctx.send(f"now = {current_time}")