File size: 11,281 Bytes
618430a |
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 |
# Ultroid - UserBot
# Copyright (C) 2021-2025 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 re, uuid, operator
from random import choice, shuffle
from akipy.async_akipy import Akinator
from telethon.errors.rpcerrorlist import BotMethodInvalidError
from telethon.events import Raw
from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
from pyUltroid._misc._decorators import ultroid_cmd
from logging import getLogger
from html import unescape
from telethon.tl.types import TextWithEntities
from pyUltroid.fns.helper import inline_mention
from pyUltroid.fns.tools import async_searcher
from telethon.errors import ChatSendStickersForbiddenError
from . import * # Ensure this import matches your project structure
games = {}
aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg"
akipyLOGS = getLogger("akipy")
@ultroid_cmd(pattern="akinator")
async def akina(e):
sta = Akinator()
games[e.chat_id] = {e.id: sta}
LOGS.info(f"Game started for chat {e.chat_id} with ID {e.id}.")
try:
m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}")
await m[0].click(e.chat_id)
akipyLOGS.info(f"Clicked inline result for chat {e.chat_id}")
except BotMethodInvalidError as err:
akipyLOGS.error(f"BotMethodInvalidError: {err}")
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:
akipyLOGS.error(f"Unexpected error: {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).strip().decode("utf-8")
dt = adt.split("_")
ch = int(dt[0])
mid = int(dt[1])
await e.edit(get_string("com_1"))
try:
await games[ch][mid].start_game(child_mode=False)
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]
await e.edit(f"Q. {games[ch][mid].question}", buttons=bts)
except KeyError:
return await e.answer(get_string("aki_1"), alert=True)
@callback(re.compile("aka_(.*)"), owner=True)
async def okah(e):
try:
mk = e.pattern_match.group(1).decode("utf-8").split("_")
#akipyLOGS.info(f"Parsed values: {mk}")
if len(mk) < 3:
akipyLOGS.error("Pattern match did not return enough parts.")
return await e.answer("Invalid data received.", alert=True)
ch = int(mk[0])
mid = int(mk[1])
ans = mk[2]
gm = games[ch][mid]
await gm.answer(ans)
# Check for the final guess in the API response
if gm.name_proposition and gm.description_proposition:
gm.win = True
text = f"It's {gm.name_proposition}\n{gm.description_proposition}"
await e.edit(text, file=gm.photo)
else:
# Game is not won yet, continue asking questions
buttons = [
[Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]],
[Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]],
]
await e.edit(gm.question, buttons=buttons)
except KeyError:
await e.answer(get_string("aki_3"))
except Exception as ex:
akipyLOGS.error(f"An unexpected error occurred: {ex}")
@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 ------------------- #
GIMAGE = "https://graph.org/file/1c51015bae5205a65fd69.jpg"
@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=GIMAGE,
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",
"CAADAgADiwMAAsSraAuoe2BwYu1sdQI",
]
@callback("delit", owner=True)
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(TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi)]
[
opts.append(
PollAnswer(TextWithEntities(unescape(a), entities=[]), str(uuid.uuid1()).split("-")[0].encode())
)
for a in q["incorrect_answers"]
]
shuffle(opts)
poll = InputMediaPoll(
Poll(
0,
TextWithEntities(
f"[{copper+1}]. " + unescape(q["question"]),
entities=[]
),
answers=opts,
public_voters=True,
quiz=True,
close_period=int(in_),
),
correct_answers=[ansi],
solution="Join @TeamUltroid",
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: UpdateMessagePollVote):
if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys():
return
if not eve.options:
# Consider as correct answer if no options selected
chat = POLLS.get(eve.poll_id)["chat"]
user = eve.peer.user_id
if not TRIVIA_CHATS.get(chat, {}).get(user):
TRIVIA_CHATS[chat][user] = 1
else:
TRIVIA_CHATS[chat][user] += 1
return
if POLLS[eve.poll_id]["answer"] != eve.options[0]:
return
chat = POLLS.get(eve.poll_id)["chat"]
user = eve.peer.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!")
|