inlinefuncs.py 25 KB

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