inlinefuncs.py 25 KB

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