forked from TeamUltroid/Ultroid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgames.py
308 lines (272 loc) · 9.69 KB
/
games.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
# Ultroid - UserBot
# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
• `{i}akinator` | `/akinator`
Start akinator game from Userbot/Assistant
• `/startgame`
Open Portal for Games
"""
import asyncio
import operator
import re
import uuid
from html import unescape
from random import choice, shuffle
import akinator
from pyUltroid.functions.helper import inline_mention
from pyUltroid.functions.tools import async_searcher
from pyUltroid.misc._decorators import ultroid_cmd
from telethon.errors.rpcerrorlist import (
BotMethodInvalidError,
ChatSendStickersForbiddenError,
)
from telethon.events import Raw
from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
from . import *
# -------------------------- Akinator ----------------------- #
games = {}
aki_photo = "https://telegra.ph/file/3cc8825c029fd0cab9edc.jpg"
@ultroid_cmd(pattern="akinator")
async def akina(e):
sta = akinator.Akinator()
games.update({e.chat_id: {e.id: sta}})
try:
m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}")
await m[0].click(e.chat_id)
except BotMethodInvalidError:
await asst.send_file(
e.chat_id,
aki_photo,
buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"),
)
except Exception as er:
return await e.eor(f"**ERROR :** `{er}`")
if e.out:
await e.delete()
@asst_cmd(pattern="akinator", owner=True)
async def _akokk(e):
await akina(e)
@callback(re.compile("aki_(.*)"), owner=True)
async def doai(e):
adt = e.pattern_match.group(1).decode("utf-8")
dt = adt.split("_")
ch = int(dt[0])
mid = int(dt[1])
await e.edit(get_string("com_1"))
try:
qu = games[ch][mid].start_game(child_mode=True)
# child mode should be promoted
except KeyError:
return await e.answer(get_string("aki_1"), alert=True)
bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]]
cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]]
bts = [bts, cts]
# ignored Back Button since it makes the Pagination looks Bad
await e.edit("Q. " + qu, buttons=bts)
@callback(re.compile("aka_(.*)"), owner=True)
async def okah(e):
mk = e.pattern_match.group(1).decode("utf-8").split("_")
ch = int(mk[0])
mid = int(mk[1])
ans = mk[2]
try:
gm = games[ch][mid]
except KeyError:
await e.answer(get_string("aki_3"))
return
text = gm.answer(ans)
if gm.progression >= 80:
gm.win()
gs = gm.first_guess
text = "It's " + gs["name"] + "\n " + gs["description"]
return await e.edit(text, file=gs["absolute_picture_path"])
bts = [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]]
cts = [
Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]
]
bts = [bts, cts]
await e.edit(text, buttons=bts)
@in_pattern(re.compile("aki_?(.*)"), owner=True)
async def eiagx(e):
bts = Button.inline(get_string("aki_2"), data=e.text)
ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", [])
ans = [
await e.builder.article(
"Akinator",
type="photo",
content=ci,
text="Akinator",
thumb=ci,
buttons=bts,
include_media=True,
)
]
await e.answer(ans)
# ----------------------- Main Command ------------------- #
@asst_cmd(pattern="startgame", owner=True)
async def magic(event):
buttons = [
[Button.inline("Trivia Quiz", "trzia")],
[Button.inline("Cancel ❌", "delit")],
]
await event.reply(
get_string("games_1"),
file="https://telegra.ph/file/1c51015bae5205a65fd69.jpg",
buttons=buttons,
)
# -------------------------- Trivia ----------------------- #
TR_BTS = {}
DIFI_KEYS = ["Easy", "Medium", "Hard"]
TRIVIA_CHATS = {}
POLLS = {}
CONGO_STICKER = [
"CAADAgADSgIAAladvQrJasZoYBh68AI",
"CAADAgADXhIAAuyZKUl879mlR_dkOwI",
"CAADAgADpQAD9wLID-xfZCDwOI5LAg",
"CAADAgADjAADECECEFZM-SrKO9GgAg",
"CAADAgADSwIAAj-VzArAzNCDiGWAHAI",
"CAADAgADhQADwZxgDIuMHR9IU10iAg",
]
@callback("delit")
async def delete_it(event):
await event.delete()
@callback(re.compile("ctdown(.*)"), owner=True)
async def ct_spam(e):
n = e.data_match.group(1).decode("utf-8")
await e.answer(f"Wait {n} seconds..", alert=True)
@callback(re.compile("trzia(.*)"), owner=True)
async def choose_cata(event):
match = event.data_match.group(1).decode("utf-8")
if not match:
if TR_BTS.get("category"):
buttons = TR_BTS["category"]
else:
req = (
await async_searcher(
"https://opentdb.com/api_category.php", re_json=True
)
)["trivia_categories"]
btt = []
for i in req:
name = i["name"]
if ":" in name:
name = name.split(":")[1]
btt.append(Button.inline(name, f"trziad_{i['id']}"))
buttons = list(zip(btt[::2], btt[1::2]))
if len(btt) % 2 == 1:
buttons.append((btt[-1],))
buttons.append([Button.inline("Cancel ❌", "delit")])
TR_BTS.update({"category": buttons})
text = get_string("games_2")
elif match[0] == "d":
cat = match[1:]
buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]]
buttons.append(get_back_button("trzia"))
text = get_string("games_3")
elif match[0] == "c":
m = match[1:]
buttons = [[Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)]]
text = get_string("games_4")
elif match[0] == "t":
m_ = match[1:]
buttons = [
[Button.inline(str(i), f"trzias{m_}_{i}") for i in [10, 30, 60, 120]]
]
text = get_string("games_5")
elif match[0] == "s":
chat = event.chat_id
cat, le, nu, in_ = match[2:].split("_")
msg = await event.edit(get_string("games_6").format(le, nu))
for i in reversed(range(5)):
msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}"))
await asyncio.sleep(1)
await msg.edit(
msg.text + "\n\n• Send /cancel to stop the Quiz...", buttons=None
)
qsss = await async_searcher(
f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}",
re_json=True,
)
qs = qsss["results"]
if not qs:
await event.respond("Sorry, No Question Found for the given Criteria..")
await event.delete()
return
TRIVIA_CHATS.update({chat: {}})
for copper, q in enumerate(qs):
if TRIVIA_CHATS[chat].get("cancel") is not None:
break
ansi = str(uuid.uuid1()).split("-")[0].encode()
opts = [PollAnswer(unescape(q["correct_answer"]), ansi)]
[
opts.append(
PollAnswer(unescape(a), str(uuid.uuid1()).split("-")[0].encode())
)
for a in q["incorrect_answers"]
]
shuffle(opts)
poll = InputMediaPoll(
Poll(
0,
f"[{copper+1}]. " + unescape(q["question"]),
answers=opts,
public_voters=True,
quiz=True,
close_period=int(in_),
),
correct_answers=[ansi],
solution="Join @TheUltroid",
solution_entities=[],
)
m_ = await event.client.send_message(chat, file=poll)
POLLS.update({m_.poll.poll.id: {"chat": m_.chat_id, "answer": ansi}})
await asyncio.sleep(int(in_))
if not TRIVIA_CHATS[chat]:
await event.respond(
"No-One Got Any Score in the Quiz!\nBetter Luck Next Time!"
)
else:
try:
await event.respond(file=choice(CONGO_STICKER))
except ChatSendStickersForbiddenError:
pass
LBD = "🎯 **Scoreboard of the Quiz.**\n\n"
TRC = TRIVIA_CHATS[chat]
if "cancel" in TRC.keys():
del TRC["cancel"]
for userid, user_score in dict(
sorted(TRC.items(), key=operator.itemgetter(1), reverse=True)
).items():
user = inline_mention(await event.client.get_entity(userid))
LBD += f"••• {user} - {user_score}\n"
await event.respond(LBD)
del TRIVIA_CHATS[chat]
list_ = list(POLLS.copy().keys())
for key in list_:
if POLLS[key]["chat"] == chat:
del POLLS[key]
return
await event.edit(text, buttons=buttons)
@asst.on(
Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id))
)
async def pollish(eve):
if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys():
return
if POLLS[eve.poll_id]["answer"] != eve.options[0]:
return
chat = POLLS.get(eve.poll_id)["chat"]
user = eve.user_id
if not TRIVIA_CHATS.get(chat, {}).get(user):
TRIVIA_CHATS[chat][user] = 1
else:
TRIVIA_CHATS[chat][user] += 1
@asst_cmd("cancel", owner=True, func=lambda x: TRIVIA_CHATS.get(x.chat_id))
async def cancelish(event):
chat = TRIVIA_CHATS.get(event.chat_id)
chat.update({"cancel": True})
await event.respond("Cancelled!")