inlinefuncs.py 25 KB

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