inlinefuncs.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. """
  2. MIT License
  3. Copyright (c) 2021 TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. import asyncio
  21. import os
  22. import sys
  23. from html import escape
  24. from re import sub as re_sub
  25. from sys import version as pyver
  26. from time import ctime, time
  27. from fuzzysearch import find_near_matches
  28. from motor import version as mongover
  29. from pykeyboard import InlineKeyboard
  30. from pyrogram import __version__ as pyrover
  31. from pyrogram import filters
  32. from pyrogram.raw.functions import Ping
  33. from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
  34. InlineQueryResultArticle, InlineQueryResultPhoto,
  35. InputTextMessageContent)
  36. from search_engine_parser import GoogleSearch
  37. from wbb import (BOT_USERNAME, MESSAGE_DUMP_CHAT, SUDOERS, USERBOT_ID,
  38. USERBOT_NAME, USERBOT_USERNAME, app, app2, arq)
  39. from wbb.core.keyboard import ikb
  40. from wbb.core.tasks import _get_tasks_text, all_tasks, rm_task
  41. from wbb.core.types import InlineQueryResultCachedDocument
  42. from wbb.modules.info import get_chat_info, get_user_info
  43. from wbb.modules.music import download_youtube_audio
  44. from wbb.utils.functions import test_speedtest
  45. from wbb.utils.pastebin import paste
  46. keywords_list = [
  47. "image",
  48. "wall",
  49. "tmdb",
  50. "lyrics",
  51. "exec",
  52. "speedtest",
  53. "search",
  54. "ping",
  55. "tr",
  56. "ud",
  57. "yt",
  58. "info",
  59. "google",
  60. "torrent",
  61. "wiki",
  62. "music",
  63. "ytmusic",
  64. ]
  65. async def inline_help_func(__HELP__):
  66. buttons = InlineKeyboard(row_width=4)
  67. buttons.add(
  68. *[
  69. (InlineKeyboardButton(text=i, switch_inline_query_current_chat=i))
  70. for i in keywords_list
  71. ]
  72. )
  73. answerss = [
  74. InlineQueryResultArticle(
  75. title="Inline Commands",
  76. description="Help Related To Inline Usage.",
  77. input_message_content=InputTextMessageContent(
  78. "Click A Button To Get Started."
  79. ),
  80. thumb_url="https://hamker.me/cy00x5x.png",
  81. reply_markup=buttons,
  82. ),
  83. InlineQueryResultArticle(
  84. title="Github Repo",
  85. description="Get Github Respository Of Bot.",
  86. input_message_content=InputTextMessageContent(
  87. "https://github.com/thehamkercat/WilliamButcherBot"
  88. ),
  89. thumb_url="https://hamker.me/gjc9fo3.png",
  90. ),
  91. ]
  92. answerss = await alive_function(answerss)
  93. return answerss
  94. async def alive_function(answers):
  95. buttons = InlineKeyboard(row_width=2)
  96. bot_state = "Dead" if not await app.get_me() else "Alive"
  97. ubot_state = "Dead" if not await app2.get_me() else "Alive"
  98. buttons.add(
  99. InlineKeyboardButton("Stats", callback_data="stats_callback"),
  100. InlineKeyboardButton(
  101. "Go Inline!", switch_inline_query_current_chat=""
  102. ),
  103. )
  104. msg = f"""
  105. **[William✨](https://github.com/thehamkercat/WilliamButcherBot):**
  106. **MainBot:** `{bot_state}`
  107. **UserBot:** `{ubot_state}`
  108. **Python:** `{pyver.split()[0]}`
  109. **Pyrogram:** `{pyrover}`
  110. **MongoDB:** `{mongover}`
  111. **Platform:** `{sys.platform}`
  112. **Profiles:** [BOT](t.me/{BOT_USERNAME}) | [UBOT](t.me/{USERBOT_USERNAME})
  113. """
  114. answers.append(
  115. InlineQueryResultArticle(
  116. title="Alive",
  117. description="Check Bot's Stats",
  118. thumb_url="https://static2.aniimg.com/upload/20170515/414/c/d/7/cd7EEF.jpg",
  119. input_message_content=InputTextMessageContent(
  120. msg, disable_web_page_preview=True
  121. ),
  122. reply_markup=buttons,
  123. )
  124. )
  125. return answers
  126. async def translate_func(answers, lang, tex):
  127. result = await arq.translate(tex, lang)
  128. if not result.ok:
  129. answers.append(
  130. InlineQueryResultArticle(
  131. title="Error",
  132. description=result.result,
  133. input_message_content=InputTextMessageContent(result.result),
  134. )
  135. )
  136. return answers
  137. result = result.result
  138. msg = f"""
  139. __**Translated from {result.src} to {result.dest}**__
  140. **INPUT:**
  141. {tex}
  142. **OUTPUT:**
  143. {result.translatedText}"""
  144. answers.extend(
  145. [
  146. InlineQueryResultArticle(
  147. title=f"Translated from {result.src} to {result.dest}.",
  148. description=result.translatedText,
  149. input_message_content=InputTextMessageContent(msg),
  150. ),
  151. InlineQueryResultArticle(
  152. title=result.translatedText,
  153. input_message_content=InputTextMessageContent(
  154. result.translatedText
  155. ),
  156. ),
  157. ]
  158. )
  159. return answers
  160. async def urban_func(answers, text):
  161. results = await arq.urbandict(text)
  162. if not results.ok:
  163. answers.append(
  164. InlineQueryResultArticle(
  165. title="Error",
  166. description=results.result,
  167. input_message_content=InputTextMessageContent(results.result),
  168. )
  169. )
  170. return answers
  171. results = results.result[0:48]
  172. for i in results:
  173. clean = lambda x: re_sub(r"[\[\]]", "", x)
  174. msg = f"""
  175. **Query:** {text}
  176. **Definition:** __{clean(i.definition)}__
  177. **Example:** __{clean(i.example)}__"""
  178. answers.append(
  179. InlineQueryResultArticle(
  180. title=i.word,
  181. description=clean(i.definition),
  182. input_message_content=InputTextMessageContent(msg),
  183. )
  184. )
  185. return answers
  186. async def google_search_func(answers, text):
  187. gresults = await GoogleSearch().async_search(text)
  188. limit = 0
  189. for i in gresults:
  190. if limit > 48:
  191. break
  192. limit += 1
  193. try:
  194. msg = f"""
  195. [{i['titles']}]({i['links']})
  196. {i['descriptions']}"""
  197. answers.append(
  198. InlineQueryResultArticle(
  199. title=i["titles"],
  200. description=i["descriptions"],
  201. input_message_content=InputTextMessageContent(
  202. msg, disable_web_page_preview=True
  203. ),
  204. )
  205. )
  206. except KeyError:
  207. pass
  208. return answers
  209. async def wall_func(answers, text):
  210. results = await arq.wall(text)
  211. if not results.ok:
  212. answers.append(
  213. InlineQueryResultArticle(
  214. title="Error",
  215. description=results.result,
  216. input_message_content=InputTextMessageContent(results.result),
  217. )
  218. )
  219. return answers
  220. results = results.result[0:48]
  221. for i in results:
  222. answers.append(
  223. InlineQueryResultPhoto(
  224. photo_url=i.url_image,
  225. thumb_url=i.url_thumb,
  226. caption=f"[Source]({i.url_image})",
  227. )
  228. )
  229. return answers
  230. async def torrent_func(answers, text):
  231. results = await arq.torrent(text)
  232. if not results.ok:
  233. answers.append(
  234. InlineQueryResultArticle(
  235. title="Error",
  236. description=results.result,
  237. input_message_content=InputTextMessageContent(results.result),
  238. )
  239. )
  240. return answers
  241. results = results.result[0:48]
  242. for i in results:
  243. title = i.name
  244. size = i.size
  245. seeds = i.seeds
  246. leechs = i.leechs
  247. upload_date = i.uploaded
  248. magnet = i.magnet
  249. caption = f"""
  250. **Title:** __{title}__
  251. **Size:** __{size}__
  252. **Seeds:** __{seeds}__
  253. **Leechs:** __{leechs}__
  254. **Uploaded:** __{upload_date}__
  255. **Magnet:** `{magnet}`"""
  256. description = f"{size} | {upload_date} | Seeds: {seeds}"
  257. answers.append(
  258. InlineQueryResultArticle(
  259. title=title,
  260. description=description,
  261. input_message_content=InputTextMessageContent(
  262. caption, disable_web_page_preview=True
  263. ),
  264. )
  265. )
  266. pass
  267. return answers
  268. async def youtube_func(answers, text):
  269. results = await arq.youtube(text)
  270. if not results.ok:
  271. answers.append(
  272. InlineQueryResultArticle(
  273. title="Error",
  274. description=results.result,
  275. input_message_content=InputTextMessageContent(results.result),
  276. )
  277. )
  278. return answers
  279. results = results.result[0:48]
  280. for i in results:
  281. buttons = InlineKeyboard(row_width=1)
  282. video_url = f"https://youtube.com{i.url_suffix}"
  283. buttons.add(InlineKeyboardButton("Watch", url=video_url))
  284. caption = f"""
  285. **Title:** {i.title}
  286. **Views:** {i.views}
  287. **Channel:** {i.channel}
  288. **Duration:** {i.duration}
  289. **Uploaded:** {i.publish_time}
  290. **Description:** {i.long_desc}"""
  291. description = (
  292. f"{i.views} | {i.channel} | {i.duration} | {i.publish_time}"
  293. )
  294. answers.append(
  295. InlineQueryResultArticle(
  296. title=i.title,
  297. thumb_url=i.thumbnails[0],
  298. description=description,
  299. input_message_content=InputTextMessageContent(
  300. caption, disable_web_page_preview=True
  301. ),
  302. reply_markup=buttons,
  303. )
  304. )
  305. return answers
  306. async def lyrics_func(answers, text):
  307. song = await arq.lyrics(text)
  308. if not song.ok:
  309. answers.append(
  310. InlineQueryResultArticle(
  311. title="Error",
  312. description=song.result,
  313. input_message_content=InputTextMessageContent(song.result),
  314. )
  315. )
  316. return answers
  317. lyrics = song.result
  318. song = lyrics.splitlines()
  319. song_name = song[0]
  320. artist = song[1]
  321. if len(lyrics) > 4095:
  322. lyrics = await paste(lyrics)
  323. lyrics = f"**LYRICS_TOO_LONG:** [URL]({lyrics})"
  324. msg = f"__{lyrics}__"
  325. answers.append(
  326. InlineQueryResultArticle(
  327. title=song_name,
  328. description=artist,
  329. input_message_content=InputTextMessageContent(msg),
  330. )
  331. )
  332. return answers
  333. async def tg_search_func(answers, text, user_id):
  334. if user_id not in SUDOERS:
  335. msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
  336. answers.append(
  337. InlineQueryResultArticle(
  338. title="ERROR",
  339. description="THIS FEATURE IS ONLY FOR SUDO USERS",
  340. input_message_content=InputTextMessageContent(msg),
  341. )
  342. )
  343. return answers
  344. if str(text)[-1] != ":":
  345. msg = "**ERROR**\n__Put A ':' After The Text To Search__"
  346. answers.append(
  347. InlineQueryResultArticle(
  348. title="ERROR",
  349. description="Put A ':' After The Text To Search",
  350. input_message_content=InputTextMessageContent(msg),
  351. )
  352. )
  353. return answers
  354. text = text[0:-1]
  355. async for message in app2.search_global(text, limit=49):
  356. buttons = InlineKeyboard(row_width=2)
  357. buttons.add(
  358. InlineKeyboardButton(
  359. text="Origin",
  360. url=message.link if message.link else "https://t.me/telegram",
  361. ),
  362. InlineKeyboardButton(
  363. text="Search again",
  364. switch_inline_query_current_chat="search",
  365. ),
  366. )
  367. name = (
  368. message.from_user.first_name
  369. if message.from_user.first_name
  370. else "NO NAME"
  371. )
  372. caption = f"""
  373. **Query:** {text}
  374. **Name:** {str(name)} [`{message.from_user.id}`]
  375. **Chat:** {str(message.chat.title)} [`{message.chat.id}`]
  376. **Date:** {ctime(message.date)}
  377. **Text:** >>
  378. {message.text.markdown if message.text else message.caption if message.caption else '[NO_TEXT]'}
  379. """
  380. result = InlineQueryResultArticle(
  381. title=name,
  382. description=message.text if message.text else "[NO_TEXT]",
  383. reply_markup=buttons,
  384. input_message_content=InputTextMessageContent(
  385. caption, disable_web_page_preview=True
  386. ),
  387. )
  388. answers.append(result)
  389. return answers
  390. async def music_inline_func(answers, query):
  391. chat_id = -1001445180719
  392. group_invite = "https://t.me/joinchat/vSDE2DuGK4Y4Nzll"
  393. try:
  394. messages = [
  395. m
  396. async for m in app2.search_messages(
  397. chat_id, query, filter="audio", limit=100
  398. )
  399. ]
  400. except Exception as e:
  401. print(e)
  402. msg = f"You Need To Join Here With Your Bot And Userbot To Get Cached Music.\n{group_invite}"
  403. answers.append(
  404. InlineQueryResultArticle(
  405. title="ERROR",
  406. description="Click Here To Know More.",
  407. input_message_content=InputTextMessageContent(
  408. msg, disable_web_page_preview=True
  409. ),
  410. )
  411. )
  412. return answers
  413. messages_ids_and_duration = []
  414. for f_ in messages:
  415. messages_ids_and_duration.append(
  416. {
  417. "message_id": f_.message_id,
  418. "duration": f_.audio.duration if f_.audio.duration else 0,
  419. }
  420. )
  421. messages = list(
  422. {v["duration"]: v for v in messages_ids_and_duration}.values()
  423. )
  424. messages_ids = [ff_["message_id"] for ff_ in messages]
  425. messages = await app.get_messages(chat_id, messages_ids[0:48])
  426. return [
  427. InlineQueryResultCachedDocument(
  428. file_id=message_.audio.file_id,
  429. title=message_.audio.title,
  430. )
  431. for message_ in messages
  432. ]
  433. async def wiki_func(answers, text):
  434. data = await arq.wiki(text)
  435. if not data.ok:
  436. answers.append(
  437. InlineQueryResultArticle(
  438. title="Error",
  439. description=data.result,
  440. input_message_content=InputTextMessageContent(data.result),
  441. )
  442. )
  443. return answers
  444. data = data.result
  445. msg = f"""
  446. **QUERY:**
  447. {data.title}
  448. **ANSWER:**
  449. __{data.answer}__"""
  450. answers.append(
  451. InlineQueryResultArticle(
  452. title=data.title,
  453. description=data.answer,
  454. input_message_content=InputTextMessageContent(msg),
  455. )
  456. )
  457. return answers
  458. async def speedtest_init(query):
  459. answers = []
  460. user_id = query.from_user.id
  461. if user_id not in SUDOERS:
  462. msg = "**ERROR**\n__THIS FEATURE IS ONLY FOR SUDO USERS__"
  463. answers.append(
  464. InlineQueryResultArticle(
  465. title="ERROR",
  466. description="THIS FEATURE IS ONLY FOR SUDO USERS",
  467. input_message_content=InputTextMessageContent(msg),
  468. )
  469. )
  470. return answers
  471. msg = "**Click The Button Below To Perform A Speedtest**"
  472. button = InlineKeyboard(row_width=1)
  473. button.add(
  474. InlineKeyboardButton(text="Test", callback_data="test_speedtest")
  475. )
  476. answers.append(
  477. InlineQueryResultArticle(
  478. title="Click Here",
  479. input_message_content=InputTextMessageContent(msg),
  480. reply_markup=button,
  481. )
  482. )
  483. return answers
  484. # CallbackQuery for the function above
  485. @app.on_callback_query(filters.regex("test_speedtest"))
  486. async def test_speedtest_cq(_, cq):
  487. if cq.from_user.id not in SUDOERS:
  488. return await cq.answer("This Isn't For You!")
  489. inline_message_id = cq.inline_message_id
  490. await app.edit_inline_text(inline_message_id, "**Testing**")
  491. loop = asyncio.get_running_loop()
  492. download, upload, info = await loop.run_in_executor(None, test_speedtest)
  493. msg = f"""
  494. **Download:** `{download}`
  495. **Upload:** `{upload}`
  496. **Latency:** `{info['latency']} ms`
  497. **Country:** `{info['country']} [{info['cc']}]`
  498. **Latitude:** `{info['lat']}`
  499. **Longitude:** `{info['lon']}`
  500. """
  501. await app.edit_inline_text(inline_message_id, msg)
  502. async def pmpermit_func(answers, user_id, victim):
  503. if user_id != USERBOT_ID:
  504. return
  505. caption = f"Hi, I'm {USERBOT_NAME}, What are you here for?, You'll be blocked if you send more than 5 messages."
  506. buttons = InlineKeyboard(row_width=2)
  507. buttons.add(
  508. InlineKeyboardButton(
  509. text="To Scam You", callback_data="pmpermit to_scam_you a"
  510. ),
  511. InlineKeyboardButton(
  512. text="For promotion",
  513. callback_data="pmpermit to_scam_you a",
  514. ),
  515. InlineKeyboardButton(
  516. text="Approve me", callback_data="pmpermit approve_me a"
  517. ),
  518. InlineKeyboardButton(
  519. text="Approve", callback_data=f"pmpermit approve {victim}"
  520. ),
  521. InlineKeyboardButton(
  522. text="Block & Delete",
  523. callback_data=f"pmpermit block {victim}",
  524. ),
  525. )
  526. answers.append(
  527. InlineQueryResultArticle(
  528. title="do_not_click_here",
  529. reply_markup=buttons,
  530. input_message_content=InputTextMessageContent(caption),
  531. )
  532. )
  533. return answers
  534. async def ping_func(answers):
  535. ping = Ping(ping_id=app.rnd_id())
  536. t1 = time()
  537. await app.send(ping)
  538. t2 = time()
  539. ping = f"{str(round((t2 - t1) * 1000, 2))} ms"
  540. answers.append(
  541. InlineQueryResultArticle(
  542. title=ping,
  543. input_message_content=InputTextMessageContent(f"__**{ping}**__"),
  544. )
  545. )
  546. return answers
  547. async def yt_music_func(answers, url):
  548. if "http" not in url:
  549. url = (await arq.youtube(url)).result[0]
  550. url = f"https://youtube.com{url.url_suffix}"
  551. loop = asyncio.get_running_loop()
  552. music = await loop.run_in_executor(None, download_youtube_audio, url)
  553. if not music:
  554. msg = "**ERROR**\n__MUSIC TOO LONG__"
  555. answers.append(
  556. InlineQueryResultArticle(
  557. title="ERROR",
  558. description="MUSIC TOO LONG",
  559. input_message_content=InputTextMessageContent(msg),
  560. )
  561. )
  562. return answers
  563. (
  564. title,
  565. performer,
  566. duration,
  567. audio,
  568. thumbnail,
  569. ) = music
  570. m = await app.send_audio(
  571. MESSAGE_DUMP_CHAT,
  572. audio,
  573. title=title,
  574. duration=duration,
  575. performer=performer,
  576. thumb=thumbnail,
  577. )
  578. os.remove(audio)
  579. os.remove(thumbnail)
  580. answers.append(
  581. InlineQueryResultCachedDocument(title=title, file_id=m.audio.file_id)
  582. )
  583. return answers
  584. async def info_inline_func(answers, peer):
  585. not_found = InlineQueryResultArticle(
  586. title="PEER NOT FOUND",
  587. input_message_content=InputTextMessageContent("PEER NOT FOUND"),
  588. )
  589. try:
  590. user = await app.get_users(peer)
  591. caption, _ = await get_user_info(user, True)
  592. except IndexError:
  593. try:
  594. chat = await app.get_chat(peer)
  595. caption, _ = await get_chat_info(chat, True)
  596. except Exception:
  597. return [not_found]
  598. except Exception:
  599. return [not_found]
  600. answers.append(
  601. InlineQueryResultArticle(
  602. title="Found Peer.",
  603. input_message_content=InputTextMessageContent(
  604. caption, disable_web_page_preview=True
  605. ),
  606. )
  607. )
  608. return answers
  609. async def tmdb_func(answers, query):
  610. response = await arq.tmdb(query)
  611. if not response.ok:
  612. answers.append(
  613. InlineQueryResultArticle(
  614. title="Error",
  615. description=response.result,
  616. input_message_content=InputTextMessageContent(response.result),
  617. )
  618. )
  619. return answers
  620. results = response.result[:49]
  621. for result in results:
  622. if not result.poster and not result.backdrop:
  623. continue
  624. if not result.genre:
  625. genre = None
  626. else:
  627. genre = " | ".join(result.genre)
  628. description = result.overview[0:900] if result.overview else "None"
  629. caption = f"""
  630. **{result.title}**
  631. **Type:** {result.type}
  632. **Rating:** {result.rating}
  633. **Genre:** {genre}
  634. **Release Date:** {result.releaseDate}
  635. **Description:** __{description}__
  636. """
  637. buttons = InlineKeyboard(row_width=1)
  638. buttons.add(
  639. InlineKeyboardButton(
  640. "Search Again",
  641. switch_inline_query_current_chat="tmdb",
  642. )
  643. )
  644. answers.append(
  645. InlineQueryResultPhoto(
  646. photo_url=result.backdrop
  647. if result.backdrop
  648. else result.poster,
  649. caption=caption,
  650. title=result.title,
  651. description=f"{genre} • {result.releaseDate} • {result.rating} • {description}",
  652. reply_markup=buttons,
  653. )
  654. )
  655. return answers
  656. async def image_func(answers, query):
  657. results = await arq.image(query)
  658. if not results.ok:
  659. answers.append(
  660. InlineQueryResultArticle(
  661. title="Error",
  662. description=results.result,
  663. input_message_content=InputTextMessageContent(results.result),
  664. )
  665. )
  666. return answers
  667. results = results.result[:49]
  668. buttons = InlineKeyboard(row_width=2)
  669. buttons.add(
  670. InlineKeyboardButton(
  671. text="Search again",
  672. switch_inline_query_current_chat="image",
  673. ),
  674. )
  675. for i in results:
  676. answers.append(
  677. InlineQueryResultPhoto(
  678. title=i.title,
  679. photo_url=i.url,
  680. thumb_url=i.url,
  681. reply_markup=buttons,
  682. )
  683. )
  684. return answers
  685. async def execute_code(query):
  686. text = query.query.strip()
  687. offset = int((query.offset or 0))
  688. answers = []
  689. languages = (await arq.execute()).result
  690. if len(text.split()) == 1:
  691. answers = [
  692. InlineQueryResultArticle(
  693. title=lang,
  694. input_message_content=InputTextMessageContent(lang),
  695. )
  696. for lang in languages
  697. ][offset : offset + 25]
  698. await query.answer(
  699. next_offset=str(offset + 25),
  700. results=answers,
  701. cache_time=1,
  702. )
  703. elif len(text.split()) == 2:
  704. text = text.split()[1].strip()
  705. languages = list(
  706. filter(
  707. lambda x: find_near_matches(text, x, max_l_dist=1),
  708. languages,
  709. )
  710. )
  711. answers.extend(
  712. [
  713. InlineQueryResultArticle(
  714. title=lang,
  715. input_message_content=InputTextMessageContent(lang),
  716. )
  717. for lang in languages
  718. ][:49]
  719. )
  720. else:
  721. lang = text.split()[1]
  722. code = text.split(None, 2)[2]
  723. response = await arq.execute(lang, code)
  724. if not response.ok:
  725. answers.append(
  726. InlineQueryResultArticle(
  727. title="Error",
  728. input_message_content=InputTextMessageContent(
  729. response.result
  730. ),
  731. )
  732. )
  733. else:
  734. res = response.result
  735. stdout, stderr = escape(res.stdout), escape(res.stderr)
  736. output = stdout or stderr
  737. out = "STDOUT" if stdout else ("STDERR" if stderr else "No output")
  738. msg = f"""
  739. **{lang.capitalize()}:**
  740. ```{code}```
  741. **{out}:**
  742. ```{output}```
  743. """
  744. answers.append(
  745. InlineQueryResultArticle(
  746. title="Executed",
  747. description=output[:20],
  748. input_message_content=InputTextMessageContent(msg),
  749. )
  750. )
  751. await query.answer(results=answers, cache_time=1)
  752. async def task_inline_func(user_id):
  753. if user_id not in SUDOERS:
  754. return
  755. tasks = all_tasks()
  756. text = await _get_tasks_text()
  757. keyb = None
  758. if tasks:
  759. keyb = ikb(
  760. {i: f"cancel_task_{i}" for i in list(tasks.keys())},
  761. row_width=4,
  762. )
  763. return [
  764. InlineQueryResultArticle(
  765. title="Tasks",
  766. reply_markup=keyb,
  767. input_message_content=InputTextMessageContent(
  768. text,
  769. ),
  770. )
  771. ]
  772. @app.on_callback_query(filters.regex("^cancel_task_"))
  773. async def cancel_task_button(_, query: CallbackQuery):
  774. user_id = query.from_user.id
  775. if user_id not in SUDOERS:
  776. return await query.answer("This is not for you.")
  777. task_id = int(query.data.split("_")[-1])
  778. await rm_task(task_id)
  779. tasks = all_tasks()
  780. text = await _get_tasks_text()
  781. keyb = None
  782. if tasks:
  783. keyb = ikb({i: f"cancel_task_{i}" for i in list(tasks.keys())})
  784. await app.edit_inline_text(
  785. query.inline_message_id,
  786. text,
  787. )
  788. if keyb:
  789. await app.edit_inline_reply_markup(
  790. query.inline_message_id,
  791. keyb,
  792. )