diff --git a/.github/ISSUE_TEMPLATE/bug-reports.yml b/.github/ISSUE_TEMPLATE/bug-reports.yml
index ce59aae610ee35d60bc267eed2779c1075f467ee..9bdd4b8586a32b3753d25d70854aa7d78545d55d 100644
--- a/.github/ISSUE_TEMPLATE/bug-reports.yml
+++ b/.github/ISSUE_TEMPLATE/bug-reports.yml
@@ -30,6 +30,7 @@ body:
label: Version
description: What version of Ultroid are you running?
options:
+ - 0.3
- 0.2
- 0.1
- 0.0.9
@@ -64,4 +65,4 @@ body:
description: By submitting this issue, you agree that you have read the [docs](https://ultroid.tech) and gone through the [deploy tutorial](https://www.youtube.com/watch?v=9wF7k9qA0Q4) at first.
options:
- label: I have followed all of the above steps.
- required: true
+ required: true
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index d8c0d8797b25d072d59e9dfcdb9b821dc377cf68..734deb175073c6406a252e363996f918ff6eb461 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,4 +1,4 @@
-blank_issues_enabled: false
+blank_issues_enabled: true
contact_links:
- name: Ultroid Support
url: https://t.me/UltroidSupport
diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
index dc42a282fe93773cc76da3c9c8a080f913ee93a7..e8d655ace2d5d13975cc8c3f9780e91536593365 100644
--- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
+++ b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
@@ -6,7 +6,4 @@ detailed_description_here
### Issue Number [Optional] :
Issue Number here if your pull request close any issue or is linked to.
-----
-### What defines you?
-- [ ] Hacktoberfest Participant.
-- [ ] Contributor
+----
\ No newline at end of file
diff --git a/.github/stalebot.yml b/.github/stalebot.yml
new file mode 100644
index 0000000000000000000000000000000000000000..17665e7747a3ca0f05a1f73f947d1286f9a5063a
--- /dev/null
+++ b/.github/stalebot.yml
@@ -0,0 +1,13 @@
+# Number of days of inactivity before an issue becomes stale
+daysUntilStale: 50
+# Number of days of inactivity before a stale issue is closed
+daysUntilClose: 7
+# Label to use when marking an issue as stale
+staleLabel: inactive
+# Comment to post when marking an issue as stale. Set to `false` to disable
+markComment: >
+ This issue has been automatically marked as stale because it has not had
+ recent activity. It will be closed if no further activity occurs. Thank you
+ for your contributions.
+# Comment to post when closing a stale issue. Set to `false` to disable
+closeComment: false
\ No newline at end of file
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index 0dcbdcde69ecdbb22cce389ee503c410f7de3d85..7e9bbb834a5367359af95f47b92a1a54b18c639a 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -24,6 +24,4 @@ jobs:
languages: python
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v1
-
-# Built with ❤ by [Pipeline Foundation](https://pipeline.foundation)
\ No newline at end of file
+ uses: github/codeql-action/analyze@v1
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index fbb4d2d278f1d7920163d11bd3b6663683ad492b..a69d36986aa278af32dd2c262b039c5f9b358072 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,6 +1,12 @@
# Welcome To Contributing Guide
Any contribution done to this repository will be appreciated! 🎉
+### About Ultroid
+- **Ultroid** is Telegram Userbot, which allow you to perform many task easily.
+- It's base core is a pip package named [`pyUltroid`](https://GitHub.com/TeamUltroid/pyUltroid).
+- This repository, contains Ultroid's official plugin files.
+- moreover, Ultroid User also have an option to get more plugins available at [`UltroidAddons`](https://github.com/TeamUltroid/UltroidAddons)
+
### Issues
- Search for existing Similar issues.
- You can open a issue first before contributing, If it contain some major changes like `bug fixes` or `feature addition`.
diff --git a/Dockerfile b/Dockerfile
index e865c241287ff21749ac99b2fd9e1a504aeb327d..1551f040c5105df7f433f26bd3ba68d88abf7f03 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in .
@@ -9,14 +9,13 @@ FROM theteamultroid/ultroid:main
ENV TZ=Asia/Kolkata
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \
-
# cloning the repo and installing requirements.
&& git clone https://github.com/TeamUltroid/Ultroid.git /root/TeamUltroid/ \
&& pip3 install --no-cache-dir -r root/TeamUltroid/requirements.txt \
- && pip3 uninstall av -y && pip3 install av --no-binary av
+ && pip3 install av --no-binary av
# changing workdir
WORKDIR /root/TeamUltroid/
# start the bot
-CMD ["bash", "resources/startup/startup.sh"]
+CMD ["bash", "startup"]
diff --git a/README.md b/README.md
index 7ac65b836397a557d37a67af0a140df9f93ac27a..bde616148b8264162a99088359e9f3c91668b080 100644
--- a/README.md
+++ b/README.md
@@ -5,19 +5,20 @@
Ultroid - UserBot
-A stable pluggable Telegram userbot + Voice & Video Call music bot, based on Telethon.
+A stable pluggable Telegram userbot + Voice & Video Call music bot, based on Telethon.
+[](#)
[](https://github.com/TeamUltroid/Ultroid/stargazers)
[](https://github.com/TeamUltroid/Ultroid/fork)
[](https://github.com/TeamUltroid/Ultroid/)
-[](https://www.python.org/)
+[](https://www.python.org/)
[](https://www.codefactor.io/repository/github/teamultroid/ultroid/overview/main)
[](https://github.com/TeamUltroid/Ultroid/graphs/commit-activity)
-[](https://img.shields.io/docker/pulls/theteamultroid/ultroid?style=flat-square)
-[](https://github.com/TeamUltroid/Ultroid)
+[](https://img.shields.io/docker/pulls/theteamultroid/ultroid?style=flat-square)
+[](https://github.com/TeamUltroid/Ultroid)
[](https://github.com/TeamUltroid/Ultroid/graphs/contributors)
[](https://makeapullrequest.com)
-[](https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE)
+[](https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE)
[](https://stars.medv.io/TeamUltroid/Ultroid)
----
@@ -29,7 +30,7 @@
[](http://ultroid.tech/)
# Tutorial
-- Full Tutorial - [](https://www.youtube.com/watch?v=9wF7k9qA0Q4)
+- Full Tutorial - [](https://www.youtube.com/watch?v=0wAV7pUzhDQ)
- Tutorial to get Redis URL and password - [here.](./resources/extras/redistut.md)
---
@@ -42,16 +43,7 @@ Get the [Necessary Variables](#Necessary-Variables) and then click the button be
## Deploy Locally
- [Traditional Method](#local-deploy---traditional-method)
- [Easy Method](#local-deploy---easy-method)
-- [Latest UltroidCli](#local-deploy---latest-method)
-
-
-### Local Deploy - Latest Method
-This is the latest and most fastest method currently.
-First, go to [UltroidCli](https://github.com/BLUE-DEVIL1134/UltroidCli) and install the latest release from the Github Releases.
-Then, do as it's given in the `README.md` to add the executable to your system path.
-
-Further, take a look at the [`docs`](https://blue-devil1134.github.io/UltroidCli/) to get more information.
-
+- [Ultroid CLI](#Ultroid-CLI)
### Local Deploy - Easy Method
- Linux - `bash -c "$(curl -fsSL https://git.io/JY9UM)"`
@@ -60,14 +52,14 @@ Further, take a look at the [`docs`](https://blue-devil1134.github.io/UltroidCli
### Local Deploy - Traditional Method
- Get your [Necessary Variables](#Necessary-Variables)
-- Clone the repository:
+- Clone the repository:
`git clone https://github.com/TeamUltroid/Ultroid.git`
-- Go to the cloned folder:
+- Go to the cloned folder:
`cd Ultroid`
-- Create a virtual env:
+- Create a virtual env:
`virtualenv -p /usr/bin/python3 venv`
`. ./venv/bin/activate`
-- Install the requirements:
+- Install the requirements:
`pip(3) install -U -r re*/st*/optional-requirements.txt`
`pip(3) install -U -r requirements.txt`
- Generate your `SESSION`:
@@ -83,10 +75,23 @@ Further, take a look at the [`docs`](https://blue-devil1134.github.io/UltroidCli
(You can either edit and rename the file or make a new file named `.env`.)
- Run the bot:
- Linux Users:
- `bash resources/startup/startup.sh`
+ `bash startup`
- Windows Users:
`python(3) -m pyUltroid`
+### Ultroid CLI
+[Ultroid CLI](https://github.com/BLUE-DEVIL1134/UltroidCli) is a command-line interface for deploying Ultroid.
+
+- **Installing** -
+Run the following code on a terminal, with curl installed.
+`ver=$(curl https://raw.githubusercontent.com/BLUE-DEVIL1134/UltroidCli/main/version.txt) && curl -L -o ultroid https://github.com/BLUE-DEVIL1134/UltroidCli/releases/download/$ver/ultroid.exe`
+OR
+Go to [UltroidCli](https://github.com/BLUE-DEVIL1134/UltroidCli) and install the version release from the Github Releases. Add the executable to your system path as specified in the [Readme](https://github.com/BLUE-DEVIL1134/UltroidCli#how-to-use-ultroidcli-).
+
+- **Documentation** -
+Take a look at the [`docs`](https://blue-devil1134.github.io/UltroidCli/) for more detailed information.
+
+---
## Necessary Variables
- `SESSION` - SessionString for your accounts login session. Get it from [here](#Session-String)
- `REDIS_URI` - Redis endpoint URL, from [redislabs](http://redislabs.com/), tutorial [here.](./resources/extras/redistut.md)
@@ -100,14 +105,17 @@ Different ways to get your `SESSION`:
* Termux : `sh -c "$(curl -fsSL https://da.gd/termux-tel)"`
* TelegramBot : [@SessionGeneratorBot](https://t.me/SessionGeneratorBot)
-Made with 💕 by [@TeamUltroid](https://t.me/TeamUltroid).
+---
# License
+[](LICENSE)
Ultroid is licensed under [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.en.html) v3 or later.
-[](LICENSE)
+---
# Credits
* [](https://t.me/UltroidDevs)
* [Lonami](https://github.com/LonamiWebs/) for [Telethon.](https://github.com/LonamiWebs/Telethon)
* [MarshalX](https://github.com/MarshalX) for [PyTgCalls.](https://github.com/MarshalX/tgcalls)
+
+> Made with 💕 by [@TeamUltroid](https://t.me/TeamUltroid).
diff --git a/assistant/__init__.py b/assistant/__init__.py
index 6a9e20f47c2f72f5489eefc36b7e4fa6d067e673..374f650a613bc4645e3be18575d622c4d0dcab8b 100644
--- a/assistant/__init__.py
+++ b/assistant/__init__.py
@@ -1,12 +1,14 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
from pyUltroid import *
+from pyUltroid import _ult_cache
from pyUltroid.functions.helper import *
+from pyUltroid.functions.tools import get_stored_file
from pyUltroid.misc import owner_and_sudos
from pyUltroid.misc._assistant import asst_cmd, callback, in_pattern
from telethon import Button, custom
@@ -14,15 +16,15 @@ from telethon import Button, custom
from plugins import ATRA_COL
from strings import get_languages, get_string, language
-OWNER_NAME = ultroid_bot.me.first_name
-OWNER_ID = ultroid_bot.me.id
+OWNER_NAME = ultroid_bot.full_name
+OWNER_ID = ultroid_bot.uid
AST_PLUGINS = {}
async def setit(event, name, value):
try:
- udB.set(name, value)
+ udB.set_key(name, value)
except BaseException:
return await event.edit("`Something Went Wrong`")
diff --git a/assistant/api_setter.py b/assistant/api_setter.py
deleted file mode 100644
index c662560e235c760192180a94597b279143e999b8..0000000000000000000000000000000000000000
--- a/assistant/api_setter.py
+++ /dev/null
@@ -1,94 +0,0 @@
-# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
-#
-# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
-# PLease read the GNU Affero General Public License in
-# .
-
-from telethon import events
-
-from . import *
-
-# main menu for api setting
-
-
-@callback("apiset", owner=True)
-async def apiset(event: events.CallbackQuery):
- await event.edit(
- get_string("ast_1"),
- buttons=[
- [Button.inline("Remove.bg API", data="rmbg")],
- [Button.inline("DEEP API", data="dapi")],
- [Button.inline("OCR API", data="oapi")],
- [Button.inline("« Back", data="setter")],
- ],
- )
-
-
-@callback("rmbg", owner=True)
-async def rmbgapi(event: events.CallbackQuery):
- await event.delete()
- pru = event.sender_id
- var = "RMBG_API"
- name = "Remove.bg API Key"
- async with event.client.conversation(pru) as conv:
- await conv.send_message(get_string("ast_2"))
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("apiset"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to {themssg}",
- buttons=get_back_button("apiset"),
- )
-
-
-@callback("dapi", owner=True)
-async def rmbgapi(event: events.CallbackQuery):
- await event.delete()
- pru = event.sender_id
- var = "DEEP_API"
- name = "DEEP AI API Key"
- async with event.client.conversation(pru) as conv:
- await conv.send_message("Get Your Deep Api from deepai.org and send here.")
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("apiset"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to {themssg}",
- buttons=get_back_button("apiset"),
- )
-
-
-@callback("oapi", owner=True)
-async def rmbgapi(event: events.CallbackQuery):
- await event.delete()
- pru = event.sender_id
- var = "OCR_API"
- name = "OCR API Key"
- async with event.client.conversation(pru) as conv:
- await conv.send_message("Get Your OCR api from ocr.space Send Send Here.")
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("apiset"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to {themssg}",
- buttons=get_back_button("apiset"),
- )
diff --git a/assistant/callbackstuffs.py b/assistant/callbackstuffs.py
index 9dacb43b89135eca39bb72d138c12c4d1a273e50..d684aa1ed50565955536e749ce3461edf6205f62 100644
--- a/assistant/callbackstuffs.py
+++ b/assistant/callbackstuffs.py
@@ -1,32 +1,39 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
+
+import asyncio
import re
import sys
+import time
from asyncio.exceptions import TimeoutError as AsyncTimeOut
from os import execl, remove
from random import choice
-from pyUltroid.functions.gdrive import authorize, create_token_file
-from pyUltroid.functions.tools import get_paste, telegraph_client
+from bs4 import BeautifulSoup as bs
+from pyUltroid.functions.gDrive import GDriveManager
+from pyUltroid.functions.helper import fast_download, progress, uploader
+from pyUltroid.functions.tools import (
+ Carbon,
+ async_searcher,
+ get_paste,
+ telegraph_client,
+)
from pyUltroid.startup.loader import Loader
from telegraph import upload_file as upl
-from telethon import events
+from telethon import Button, events
from telethon.tl.types import MessageMediaWebPage
from telethon.utils import get_peer_id
-try:
- from carbonnow import Carbon
-except ImportError:
- Carbon = None
from . import *
# --------------------------------------------------------------------#
telegraph = telegraph_client()
+GDrive = GDriveManager()
# --------------------------------------------------------------------#
@@ -34,13 +41,198 @@ def text_to_url(event):
"""function to get media url (with|without) Webpage"""
if isinstance(event.media, MessageMediaWebPage):
webpage = event.media.webpage
- if webpage and webpage.type in ["photo"]:
+ if not isinstance(webpage, types.WebPageEmpty) and webpage.type in ["photo"]:
return webpage.display_url
return event.text
# --------------------------------------------------------------------#
+_buttons = {
+ "otvars": {
+ "text": "Other Variables to set for @TheUltroid:",
+ "buttons": [
+ [
+ Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"),
+ Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"),
+ ],
+ [
+ Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ", data="sudo"),
+ Button.inline("Hᴀɴᴅʟᴇʀ", data="hhndlr"),
+ ],
+ [
+ Button.inline("Exᴛʀᴀ Pʟᴜɢɪɴs", data="plg"),
+ Button.inline("Aᴅᴅᴏɴs", data="eaddon"),
+ ],
+ [
+ Button.inline("Eᴍᴏᴊɪ ɪɴ Hᴇʟᴘ", data="emoj"),
+ Button.inline("Sᴇᴛ ɢDʀɪᴠᴇ", data="gdrive"),
+ ],
+ [
+ Button.inline("Iɴʟɪɴᴇ Pɪᴄ", data="inli_pic"),
+ Button.inline("Sᴜᴅᴏ HNDLR", data="shndlr"),
+ ],
+ [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ", "cbs_oofdm")],
+ [Button.inline("« Bᴀᴄᴋ", data="setter")],
+ ],
+ },
+ "sfban": {
+ "text": "SuperFban Settings:",
+ "buttons": [
+ [Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")],
+ [Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="abs_sfexf")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
+ ],
+ },
+ "apauto": {
+ "text": "This'll auto approve on outgoing messages",
+ "buttons": [
+ [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")],
+ [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
+ ],
+ },
+ "alabs_vcstm": {
+ "text": f"Customise your {HNDLR}alive. Choose from the below options -",
+ "buttons": [
+ [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="abs_alvtx")],
+ [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")],
+ [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")],
+ [Button.inline("« Bᴀᴄᴋ", data="setter")],
+ ],
+ },
+ "pmcstm": {
+ "text": "Customise your PMPERMIT Settings -",
+ "buttons": [
+ [
+ Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"),
+ Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"),
+ ],
+ [
+ Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="cbs_apauto"),
+ Button.inline("PMLOGGER", data="pml"),
+ ],
+ [
+ Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"),
+ Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"),
+ ],
+ [Button.inline("PMPermit Type", data="cbs_pmtype")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")],
+ ],
+ },
+ "pmtype": {
+ "text": "Select the type of PMPermit needed.",
+ "buttons": [
+ [Button.inline("Inline", data="inpm_in")],
+ [Button.inline("Normal", data="inpm_no")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
+ ],
+ },
+ "ppmset": {
+ "text": "PMPermit Settings:",
+ "buttons": [
+ [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")],
+ [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")],
+ [Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="cbs_pmcstm")],
+ [Button.inline("« Bᴀᴄᴋ", data="setter")],
+ ],
+ },
+ "chatbot": {
+ "text": "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)",
+ "buttons": [
+ [
+ Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot"),
+ Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot"),
+ ],
+ [
+ Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel"),
+ Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew"),
+ ],
+ [Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")],
+ [Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")],
+ [Button.inline("« Bᴀᴄᴋ", data="setter")],
+ ],
+ },
+ "vcb": {
+ "text": "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)",
+ "buttons": [
+ [Button.inline("VC Sᴇssɪᴏɴ", data="abs_vcs")],
+ [Button.inline("« Bᴀᴄᴋ", data="setter")],
+ ],
+ },
+ "oofdm": {
+ "text": "About [Dual Mode](https://t.me/UltroidUpdates/18)",
+ "buttons": [
+ [
+ Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof"),
+ Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof"),
+ ],
+ [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")],
+ [Button.inline("« Back", data="cbs_otvars")],
+ ],
+ },
+ "apiset": {
+ "text": get_string("ast_1"),
+ "buttons": [
+ [Button.inline("Remove.bg API", data="abs_rmbg")],
+ [Button.inline("DEEP API", data="abs_dapi")],
+ [Button.inline("OCR API", data="abs_oapi")],
+ [Button.inline("« Back", data="setter")],
+ ],
+ },
+}
+
+_convo = {
+ "rmbg": {
+ "var": "RMBG_API",
+ "name": "Remove.bg API Key",
+ "text": get_string("ast_2"),
+ "back": "cbs_apiset",
+ },
+ "dapi": {
+ "var": "DEEP_AI",
+ "name": "Deep AI Api Key",
+ "text": "Get Your Deep Api from deepai.org and send here.",
+ "back": "cbs_apiset",
+ },
+ "oapi": {
+ "var": "OCR_API",
+ "name": "Ocr Api Key",
+ "text": "Get Your OCR api from ocr.space and send that Here.",
+ "back": "cbs_apiset",
+ },
+ "pmlgg": {
+ "var": "PMLOGGROUP",
+ "name": "Pm Log Group",
+ "text": "Send chat id of chat which you want to save as Pm log Group.",
+ "back": "pml",
+ },
+ "vcs": {
+ "var": "VC_SESSION",
+ "name": "Vc Session",
+ "text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.",
+ "back": "cbs_vcb",
+ },
+ "settag": {
+ "var": "TAG_LOG",
+ "name": "Tag Log Group",
+ "text": f"Make a group, add your assistant and make it admin.\nGet the `{HNDLR}id` of that group and send it here for tag logs.\n\nUse /cancel to cancel.",
+ "back": "taglog",
+ },
+ "alvtx": {
+ "var": "ALIVE_TEXT",
+ "name": "Alive Text",
+ "text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.",
+ "back": "cbs_alvcstm",
+ },
+ "sfexf": {
+ "var": "EXCLUDE_FED",
+ "name": "Excluded Fed",
+ "text": "Send the Fed IDs you want to exclude in the ban. Split by a space.\neg`id1 id2 id3`\nSet is as `None` if you dont want any.\nUse /cancel to go back.",
+ "back": "cbs_sfban",
+ },
+}
+
TOKEN_FILE = "resources/auths/auth_token.txt"
@@ -52,33 +244,34 @@ TOKEN_FILE = "resources/auths/auth_token.txt"
owner=True,
)
async def send(eve):
- name = (eve.data_match.group(1)).decode("UTF-8")
+ key, name = (eve.data_match.group(1)).decode("UTF-8").split("_")
thumb = "resources/extras/inline.jpg"
await eve.answer("■ Sending ■")
- if name.startswith("def"):
- plug_name = name.replace("def_plugin_", "")
- plugin = f"plugins/{plug_name}.py"
- data = "back"
- elif name.startswith("add"):
- plug_name = name.replace("add_plugin_", "")
- plugin = f"addons/{plug_name}.py"
- data = "buck"
- else:
- plug_name = name.replace("vc_plugin_", "")
- plugin = f"vcbot/{plug_name}.py"
- data = "vc_helper"
+ data = f"uh_{key}_"
+ index = None
+ if "|" in name:
+ name, index = name.split("|")
+ key = "plugins" if key == "Official" else key.lower()
+ plugin = f"{key}/{name}.py"
+ _ = f"pasta-{plugin}"
+ if index is not None:
+ data += f"|{index}"
+ _ += f"|{index}"
buttons = [
[
Button.inline(
"« Pᴀsᴛᴇ »",
- data=f"pasta-{plugin}",
+ data=_,
)
],
[
Button.inline("« Bᴀᴄᴋ", data=data),
],
]
- await eve.edit(file=plugin, thumb=thumb, buttons=buttons)
+ try:
+ await eve.edit(file=plugin, thumb=thumb, buttons=buttons)
+ except Exception as er:
+ await eve.answer(str(er), alert=True)
heroku_api, app_name = Var.HEROKU_API, Var.HEROKU_APP_NAME
@@ -130,24 +323,28 @@ async def update(eve):
execl(sys.executable, sys.executable, "-m", "pyUltroid")
-@callback("changes", owner=True)
+@callback(re.compile("changes(.*)"), owner=True)
async def changes(okk):
+ match = okk.data_match.group(1).decode("utf-8")
await okk.answer(get_string("clst_3"))
repo = Repo.init()
- ac_br = repo.active_branch
- button = (Button.inline("Update Now", data="updatenow"),)
- changelog, tl_chnglog = gen_chlog(repo, f"HEAD..upstream/{ac_br}")
+ button = [[Button.inline("Update Now", data="updatenow")]]
+ changelog, tl_chnglog = await gen_chlog(
+ repo, f"HEAD..upstream/{repo.active_branch}"
+ )
cli = "\n\nClick the below button to update!"
- if Carbon:
+ if not match:
try:
+ if len(tl_chnglog) > 700:
+ tl_chnglog = tl_chnglog[:700] + "..."
+ button.append([Button.inline("View Complete", "changesall")])
await okk.edit("• Writing Changelogs 📝 •")
- carbon = Carbon(
- base_url="https://carbonara-42.herokuapp.com/api/cook",
+ img = await Carbon(
+ file_name="changelog",
code=tl_chnglog,
- background=choice(ATRA_COL),
+ backgroundColor=choice(ATRA_COL),
language="md",
)
- img = await carbon.memorize("changelog")
return await okk.edit(
f"**• Ultroid Userbot •**{cli}", file=img, buttons=button
)
@@ -162,7 +359,7 @@ async def changes(okk):
await okk.edit(
get_string("upd_5"),
file="ultroid_updates.txt",
- buttons=Button.inline("Update Now", data="updatenow"),
+ buttons=button,
)
remove("ultroid_updates.txt")
return
@@ -181,39 +378,83 @@ async def changes(okk):
)
async def _(e):
ok = (e.data_match.group(1)).decode("UTF-8")
+ index = None
+ if "|" in ok:
+ ok, index = ok.split("|")
with open(ok, "r") as hmm:
_, key = await get_paste(hmm.read())
link = "https://spaceb.in/" + key
raw = f"https://spaceb.in/api/v1/documents/{key}/raw"
if not _:
return await e.answer(key[:30], alert=True)
- data = "back" if ok.startswith("plugins") else "buck"
+ if ok.startswith("addons"):
+ key = "Addons"
+ elif ok.startswith("vcbot"):
+ key = "VCBot"
+ else:
+ key = "Official"
+ data = f"uh_{key}_"
+ if index is not None:
+ data += f"|{index}"
await e.edit(
- f"Pasted\n👉 [Link]\n👉 [Raw Link]",
- buttons=Button.inline("« Bᴀᴄᴋ", data=data),
- link_preview=False,
- parse_mode="html",
+ "",
+ buttons=[
+ [Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)],
+ [Button.inline("« Bᴀᴄᴋ", data=data)],
+ ],
)
+@callback(re.compile("cbs_(.*)"), owner=True)
+async def _edit_to(event):
+ match = event.data_match.group(1).decode("utf-8")
+ data = _buttons.get(match)
+ if not data:
+ return
+ await event.edit(data["text"], buttons=data["buttons"], link_preview=False)
+
+
+@callback(re.compile("abs_(.*)"), owner=True)
+async def convo_handler(event: events.CallbackQuery):
+ match = event.data_match.group(1).decode("utf-8")
+ if not _convo.get(match):
+ return
+ await event.delete()
+ get_ = _convo[match]
+ back = get_["back"]
+ async with event.client.conversation(event.sender_id) as conv:
+ await conv.send_message(get_["text"])
+ response = conv.wait_event(events.NewMessage(chats=event.sender_id))
+ response = await response
+ themssg = response.message.message
+ if themssg == "/cancel":
+ return await conv.send_message(
+ "Cancelled!!",
+ buttons=get_back_button(back),
+ )
+ await setit(event, get_["var"], themssg)
+ await conv.send_message(
+ f"{get_['name']} changed to `{themssg}`",
+ buttons=get_back_button(back),
+ )
+
+
@callback("authorise", owner=True)
async def _(e):
if not e.is_private:
return
- if not udB.get("GDRIVE_CLIENT_ID"):
- return await e.edit(
- "Client ID and Secret is Empty.\nFill it First.",
- buttons=Button.inline("Back", data="gdrive"),
- )
- storage = await create_token_file(TOKEN_FILE, e)
- authorize(TOKEN_FILE, storage)
- f = open(TOKEN_FILE)
- token_file_data = f.read()
- udB.set("GDRIVE_TOKEN", token_file_data)
- await e.reply(
- "`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`",
- buttons=Button.inline("Main Menu", data="setter"),
- )
+ url = GDrive._create_token_file()
+ await e.edit("Go to the below link and send the code!")
+ async with asst.conversation(e.sender_id) as conv:
+ await conv.send_message(url)
+ code = await conv.get_response()
+ if GDrive._create_token_file(code=code.text):
+ await conv.send_message(
+ "`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`",
+ buttons=Button.inline("Main Menu", data="setter"),
+ )
+ else:
+ await conv.send_message("Wrong code! Click authorise again.")
@callback("folderid", owner=True, func=lambda x: x.is_private)
@@ -226,47 +467,17 @@ async def _(e):
+ "1. Open Google Drive App.\n"
+ "2. Create Folder.\n"
+ "3. Make that folder public.\n"
- + "4. Copy link of that folder.\n"
- + "5. Send all characters which is after id= .",
+ + "4. Send link of that folder."
)
async with asst.conversation(e.sender_id) as conv:
reply = conv.wait_event(events.NewMessage(from_users=e.sender_id))
repl = await reply
- udB.set("GDRIVE_FOLDER_ID", repl.text)
- await repl.reply(
- "Success Now You Can Authorise.",
- buttons=get_back_button("gdrive"),
- )
-
-
-@callback("clientsec", owner=True)
-async def _(e):
- if not e.is_private:
- return
- await e.edit("Send your CLIENT SECRET")
- async with asst.conversation(e.sender_id) as conv:
- reply = conv.wait_event(events.NewMessage(from_users=e.sender_id))
- repl = await reply
- udB.set("GDRIVE_CLIENT_SECRET", repl.text)
+ id = repl.text
+ if id.startswith("https"):
+ id = id.split("?id=")[-1]
+ udB.set_key("GDRIVE_FOLDER_ID", id)
await repl.reply(
- "Success!\nNow You Can Authorise or add FOLDER ID.",
- buttons=get_back_button("gdrive"),
- )
-
-
-@callback("clientid", owner=True)
-async def _(e):
- if not e.is_private:
- return
- await e.edit("Send your CLIENT ID ending with .com")
- async with asst.conversation(e.sender_id) as conv:
- reply = conv.wait_event(events.NewMessage(from_users=e.sender_id))
- repl = await reply
- if not repl.text.endswith(".com"):
- return await repl.reply("`Wrong CLIENT ID`")
- udB.set("GDRIVE_CLIENT_ID", repl.text)
- await repl.reply(
- "Success now set CLIENT SECRET",
+ "`Success.`",
buttons=get_back_button("gdrive"),
)
@@ -276,77 +487,28 @@ async def _(e):
if not e.is_private:
return
await e.edit(
- "Go [here](https://console.developers.google.com/flows/enableapi?apiid=drive) and get your CLIENT ID and CLIENT SECRET",
+ "Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)",
buttons=[
[
- Button.inline("Cʟɪᴇɴᴛ Iᴅ", data="clientid"),
- Button.inline("Cʟɪᴇɴᴛ Sᴇᴄʀᴇᴛ", data="clientsec"),
+ Button.inline("Folder ID", data="folderid"),
+ Button.inline("Authorise", data="authorise"),
],
- [
- Button.inline("Fᴏʟᴅᴇʀ Iᴅ", data="folderid"),
- Button.inline("Aᴜᴛʜᴏʀɪsᴇ", data="authorise"),
- ],
- [Button.inline("« Bᴀᴄᴋ", data="otvars")],
+ [Button.inline("« Back", data="cbs_otvars")],
],
link_preview=False,
)
-@callback("otvars", owner=True)
-async def otvaar(event):
- await event.edit(
- "Other Variables to set for @TheUltroid:",
- buttons=[
- [
- Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"),
- Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="sfban"),
- ],
- [
- Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ", data="sudo"),
- Button.inline("Hᴀɴᴅʟᴇʀ", data="hhndlr"),
- ],
- [
- Button.inline("Exᴛʀᴀ Pʟᴜɢɪɴs", data="plg"),
- Button.inline("Aᴅᴅᴏɴs", data="eaddon"),
- ],
- [
- Button.inline("Eᴍᴏᴊɪ ɪɴ Hᴇʟᴘ", data="emoj"),
- Button.inline("Sᴇᴛ ɢDʀɪᴠᴇ", data="gdrive"),
- ],
- [
- Button.inline("Iɴʟɪɴᴇ Pɪᴄ", data="inli_pic"),
- Button.inline("Sᴜᴅᴏ HNDLR", data="shndlr"),
- ],
- [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ", "oofdm")],
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
- ],
- )
-
-
-@callback("oofdm", owner=True)
-async def euwhe(event):
- BT = [
- [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof")],
- [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof")],
- [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")],
- ]
- await event.edit(
- "About [Dual Mode](https://t.me/UltroidUpdates/18)",
- buttons=BT,
- link_preview=False,
- )
-
-
@callback("dmof", owner=True)
async def rhwhe(e):
- if udB.get("DUAL_MODE"):
- udB.delete("DUAL_MODE")
+ if udB.get_key("DUAL_MODE"):
+ udB.del_key("DUAL_MODE")
key = "Off"
else:
- udB.set("DUAL_MODE", "True")
+ udB.set_key("DUAL_MODE", "True")
key = "On"
Msg = "Dual Mode : " + key
- await e.edit(Msg, buttons=get_back_button("otvars"))
+ await e.edit(Msg, buttons=get_back_button("cbs_otvars"))
@callback("dmhn", owner=True)
@@ -355,7 +517,7 @@ async def hndlrr(event):
pru = event.sender_id
var = "DUAL_HNDLR"
name = "Dual Handler"
- CH = udB.get(var) or "/"
+ CH = udB.get_key(var) or "/"
async with event.client.conversation(pru) as conv:
await conv.send_message(
f"Send The Symbol Which u want as Handler/Trigger to use your Assistant bot\nUr Current Handler is [ `{CH}` ]\n\n use /cancel to cancel.",
@@ -366,18 +528,18 @@ async def hndlrr(event):
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
@@ -395,18 +557,18 @@ async def emoji(event):
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", HNDLR)):
await conv.send_message(
"Incorrect Emoji",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}\n",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
@@ -426,12 +588,12 @@ async def pluginch(event):
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", HNDLR)):
await conv.send_message(
"Incorrect channel",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
@@ -440,7 +602,7 @@ async def pluginch(event):
name,
themssg,
),
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
@@ -460,23 +622,23 @@ async def hndlrr(event):
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", "#", "@")):
await conv.send_message(
"This cannot be used as handler",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
@@ -497,72 +659,48 @@ async def hndlrr(event):
if themssg == "/cancel":
await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif len(themssg) > 1:
await conv.send_message(
"Incorrect Handler",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
elif themssg.startswith(("/", "#", "@")):
await conv.send_message(
"This cannot be used as handler",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
else:
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
- buttons=get_back_button("otvars"),
+ buttons=get_back_button("cbs_otvars"),
)
@callback("taglog", owner=True)
async def tagloggrr(e):
- if not udB.get("TAG_LOG"):
- BUTTON = [Button.inline("SET TAG LOG", data="settag")]
- else:
- BUTTON = [Button.inline("DELETE TAG LOG", data="deltag")]
+ BUTTON = [
+ [Button.inline("SET TAG LOG", data="abs_settag")],
+ [Button.inline("DELETE TAG LOG", data="deltag")],
+ get_back_button("cbs_otvars"),
+ ]
await e.edit(
"Choose Options",
- buttons=[BUTTON, [Button.inline("« Bᴀᴄᴋ", data="otvars")]],
+ buttons=BUTTON,
)
@callback("deltag", owner=True)
async def _(e):
- udB.delete("TAG_LOG")
- await e.answer("Done!!! TAG lOG Off")
-
-
-@callback("settag", owner=True)
-async def taglogerr(event):
- await event.delete()
- pru = event.sender_id
- var = "TAG_LOG"
- name = "Tag Log Group"
- async with event.client.conversation(pru) as conv:
- await conv.send_message(
- f"Make a group, add your assistant and make it admin.\nGet the `{HNDLR}id` of that group and send it here for tag logs.\n\nUse /cancel to cancel.",
- )
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("taglog"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to {themssg}",
- buttons=get_back_button("taglog"),
- )
+ udB.del_key("TAG_LOG")
+ await e.answer("Done!!! Tag Logger has been turned Off")
@callback("eaddon", owner=True)
async def pmset(event):
- if not udB.get("ADDONS"):
+ if not udB.get_key("ADDONS"):
BT = [Button.inline("Aᴅᴅᴏɴs Oɴ", data="edon")]
else:
BT = [Button.inline("Aᴅᴅᴏɴs Oғғ", data="edof")]
@@ -570,7 +708,7 @@ async def pmset(event):
"ADDONS~ Extra Plugins:",
buttons=[
BT,
- [Button.inline("« Bᴀᴄᴋ", data="otvars")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
],
)
@@ -587,7 +725,7 @@ async def eddon(event):
@callback("edof", owner=True)
async def eddof(event):
- udB.set("ADDONS", "False")
+ udB.set_key("ADDONS", "False")
await event.edit(
"Done! ADDONS has been turned off!! After Setting All Things Do Restart",
buttons=get_back_button("eaddon"),
@@ -596,7 +734,7 @@ async def eddof(event):
@callback("sudo", owner=True)
async def pmset(event):
- if not udB.get("SUDO"):
+ if not udB.get_key("SUDO"):
BT = [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oɴ", data="onsudo")]
else:
BT = [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oғғ", data="ofsudo")]
@@ -604,7 +742,7 @@ async def pmset(event):
f"SUDO MODE ~ Some peoples can use ur Bot which u selected. To know More use `{HNDLR}help sudo`",
buttons=[
BT,
- [Button.inline("« Bᴀᴄᴋ", data="otvars")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")],
],
)
@@ -629,18 +767,6 @@ async def eddof(event):
)
-@callback("sfban", owner=True)
-async def sfban(event):
- await event.edit(
- "SuperFban Settings:",
- buttons=[
- [Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")],
- [Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="sfexf")],
- [Button.inline("« Bᴀᴄᴋ", data="otvars")],
- ],
- )
-
-
@callback("sfgrp", owner=True)
async def sfgrp(event):
await event.delete()
@@ -657,79 +783,12 @@ async def sfgrp(event):
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("sfban"),
+ buttons=get_back_button("cbs_sfban"),
)
await setit(event, var, themssg)
await conv.send_message(
f"{name} changed to {themssg}",
- buttons=get_back_button("sfban"),
- )
-
-
-@callback("sfexf", owner=True)
-async def sfexf(event):
- await event.delete()
- name = "Excluded Feds"
- var = "EXCLUDE_FED"
- pru = event.sender_id
- async with asst.conversation(pru) as conv:
- await conv.send_message(
- "Send the Fed IDs you want to exclude in the ban. Split by a space.\neg`id1 id2 id3`\nSet is as `None` if you dont want any.\nUse /cancel to go back."
- )
-
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("sfban"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to {themssg}",
- buttons=get_back_button("sfban"),
- )
-
-
-@callback("alvcstm", owner=True)
-async def alvcs(event):
- await event.edit(
- f"Customise your {HNDLR}alive. Choose from the below options -",
- buttons=[
- [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="alvtx")],
- [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")],
- [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")],
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
- ],
- )
-
-
-@callback("alvtx", owner=True)
-async def name(event):
- await event.delete()
- pru = event.sender_id
- var = "ALIVE_TEXT"
- name = "Alive Text"
- async with event.client.conversation(pru) as conv:
- await conv.send_message(
- "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.",
- )
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("alvcstm"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- "{} changed to {}\n\nAfter Setting All Things Do restart".format(
- name,
- themssg,
- ),
- buttons=get_back_button("alvcstm"),
+ buttons=get_back_button("cbs_sfban"),
)
@@ -749,7 +808,7 @@ async def media(event):
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
- buttons=get_back_button("alvcstm"),
+ buttons=get_back_button("cbs_alvcstm"),
)
except BaseException:
pass
@@ -770,71 +829,36 @@ async def media(event):
except BaseException:
return await conv.send_message(
"Terminated.",
- buttons=get_back_button("alvcstm"),
+ buttons=get_back_button("cbs_alvcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
- buttons=get_back_button("alvcstm"),
+ buttons=get_back_button("cbs_alvcstm"),
)
@callback("delmed", owner=True)
async def dell(event):
try:
- udB.delete("ALIVE_PIC")
+ udB.del_key("ALIVE_PIC")
return await event.edit(
- get_string("clst_5"), buttons=get_back_button("alvcstm")
+ get_string("clst_5"), buttons=get_back_button("cbs_alabs_vcstm")
)
except BaseException:
return await event.edit(
get_string("clst_4"),
- buttons=get_back_button("alvcstm"),
+ buttons=get_back_button("cbs_alabs_vcstm"),
)
-@callback("pmcstm", owner=True)
-async def alvcs(event):
- await event.edit(
- "Customise your PMPERMIT Settings -",
- buttons=[
- [
- Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"),
- Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"),
- ],
- [
- Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="apauto"),
- Button.inline("PMLOGGER", data="pml"),
- ],
- [
- Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"),
- Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"),
- ],
- [Button.inline("PMPermit Type", data="pmtype")],
- [Button.inline("« Bᴀᴄᴋ", data="ppmset")],
- ],
- )
-
-
-@callback("pmtype", owner=True)
-async def pmtyp(event):
- await event.edit(
- "Select the type of PMPermit needed.",
- buttons=[
- [Button.inline("Inline", data="inpm_in")],
- [Button.inline("Normal", data="inpm_no")],
- [Button.inline("« Bᴀᴄᴋ", data="pmcstm")],
- ],
- )
-
-
@callback("inpm_in", owner=True)
async def inl_on(event):
var = "INLINE_PM"
await setit(event, var, "True")
await event.edit(
"Done!! PMPermit type has been set to inline!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="pmtype")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
)
@@ -844,7 +868,7 @@ async def inl_on(event):
await setit(event, var, "False")
await event.edit(
"Done!! PMPermit type has been set to normal!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="pmtype")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]],
)
@@ -864,12 +888,12 @@ async def name(event):
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
if len(themssg) > 4090:
return await conv.send_message(
"Message too long!\nGive a shorter message please!!",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, themssg)
await conv.send_message(
@@ -877,7 +901,7 @@ async def name(event):
name,
themssg,
),
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
@@ -886,7 +910,7 @@ async def name(event):
m = range(1, 10)
tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m]
lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3]))
- lst.append([Button.inline("« Bᴀᴄᴋ", data="pmcstm")])
+ lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")])
await event.edit(
"Select the number of warnings for a user before getting blocked in PMs.",
buttons=lst,
@@ -896,16 +920,16 @@ async def name(event):
@callback(re.compile(b"wrns_(.*)"), owner=True)
async def set_wrns(event):
value = int(event.data_match.group(1).decode("UTF-8"))
- dn = udB.set("PMWARNS", value)
+ dn = udB.set_key("PMWARNS", value)
if dn:
await event.edit(
f"PM Warns Set to {value}.\nNew users will have {value} chances in PMs before getting banned.",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
else:
await event.edit(
f"Something went wrong, please check your {HNDLR}logs!",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
@@ -925,7 +949,7 @@ async def media(event):
if themssg == "/cancel":
return await conv.send_message(
"Operation cancelled!!",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
except BaseException:
pass
@@ -946,20 +970,22 @@ async def media(event):
except BaseException:
return await conv.send_message(
"Terminated.",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
await setit(event, var, url)
await conv.send_message(
f"{name} has been set.",
- buttons=get_back_button("pmcstm"),
+ buttons=get_back_button("cbs_pmcstm"),
)
@callback("delpmmed", owner=True)
async def dell(event):
try:
- udB.delete("PMPIC")
- return await event.edit(get_string("clst_5"), buttons=get_back_button("pmcstm"))
+ udB.del_key("PMPIC")
+ return await event.edit(
+ get_string("clst_5"), buttons=get_back_button("cbs_pmcstm")
+ )
except BaseException:
return await event.edit(
get_string("clst_4"),
@@ -967,35 +993,23 @@ async def dell(event):
)
-@callback("apauto", owner=True)
-async def apauto(event):
- await event.edit(
- "This'll auto approve on outgoing messages",
- buttons=[
- [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")],
- [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")],
- [Button.inline("« Bᴀᴄᴋ", data="pmcstm")],
- ],
- )
-
-
@callback("apon", owner=True)
async def apon(event):
var = "AUTOAPPROVE"
await setit(event, var, "True")
await event.edit(
"Done!! AUTOAPPROVE Started!!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="apauto")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
)
@callback("apof", owner=True)
async def apof(event):
try:
- udB.delete("AUTOAPPROVE")
+ udB.del_key("AUTOAPPROVE")
return await event.edit(
"Done! AUTOAPPROVE Stopped!!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="apauto")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]],
)
except BaseException:
return await event.edit(
@@ -1005,8 +1019,8 @@ async def apof(event):
@callback("pml", owner=True)
-async def alvcs(event):
- if not udB.get("PMLOG"):
+async def l_vcs(event):
+ if not udB.get_key("PMLOG"):
BT = [Button.inline("PMLOGGER ON", data="pmlog")]
else:
BT = [Button.inline("PMLOGGER OFF", data="pmlogof")]
@@ -1014,38 +1028,12 @@ async def alvcs(event):
"PMLOGGER This Will Forward Ur Pm to Ur Private Group -",
buttons=[
BT,
- [Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "pmlgg")],
- [Button.inline("« Bᴀᴄᴋ", data="pmcstm")],
+ [Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "abs_pmlgg")],
+ [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")],
],
)
-@callback("pmlgg", owner=True)
-async def disus(event):
- await event.delete()
- pru = event.sender_id
- var = "PMLOGGROUP"
- name = "Pm Logger Group"
- async with event.client.conversation(pru) as conv:
- await conv.send_message(
- f"Send The Chat Id of group Which u want as your {name}\n\n use /cancel to cancel.",
- )
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("pml"),
- )
- else:
- await setit(event, var, themssg)
- await conv.send_message(
- f"{name} changed to `{themssg}`",
- buttons=get_back_button("pml"),
- )
-
-
@callback("pmlog", owner=True)
async def pmlog(event):
await setit(event, "PMLOG", "True")
@@ -1058,7 +1046,7 @@ async def pmlog(event):
@callback("pmlogof", owner=True)
async def pmlogof(event):
try:
- udB.delete("PMLOG")
+ udB.del_key("PMLOG")
return await event.edit(
"Done! PMLOGGER Stopped!!",
buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]],
@@ -1070,26 +1058,13 @@ async def pmlogof(event):
)
-@callback("ppmset", owner=True)
-async def pmset(event):
- await event.edit(
- "PMPermit Settings:",
- buttons=[
- [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")],
- [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")],
- [Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="pmcstm")],
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
- ],
- )
-
-
@callback("pmon", owner=True)
async def pmonn(event):
var = "PMSETTING"
await setit(event, var, "True")
await event.edit(
"Done! PMPermit has been turned on!!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="ppmset")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
)
@@ -1099,7 +1074,7 @@ async def pmofff(event):
await setit(event, var, "False")
await event.edit(
"Done! PMPermit has been turned off!!",
- buttons=[[Button.inline("« Bᴀᴄᴋ", data="ppmset")]],
+ buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]],
)
@@ -1110,27 +1085,10 @@ async def hhh(e):
msg = await conv.get_response()
if not msg.media or msg.text.startswith("/"):
return await conv.send_message(
- "Terminated!", buttons=get_back_button("chatbot")
+ "Terminated!", buttons=get_back_button("cbs_chatbot")
)
- udB.set("STARTMEDIA", msg.file.id)
- await conv.send_message("Done!", buttons=get_back_button("chatbot"))
-
-
-@callback("chatbot", owner=True)
-async def chbot(event):
- await event.edit(
- "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)",
- buttons=[
- [Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot")],
- [Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot")],
- [Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel")],
- [Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew")],
- [Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")],
- [Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")],
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
- ],
- link_preview=False,
- )
+ udB.set_key("STARTMEDIA", msg.file.id)
+ await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
@callback("botinfe", owner=True)
@@ -1142,10 +1100,10 @@ async def hhh(e):
msg = await conv.get_response()
if msg.media or msg.text.startswith("/"):
return await conv.send_message(
- "Terminated!", buttons=get_back_button("chatbot")
+ "Terminated!", buttons=get_back_button("cbs_chatbot")
)
- udB.set("BOT_INFO_START", msg.text)
- await conv.send_message("Done!", buttons=get_back_button("chatbot"))
+ udB.set_key("BOT_INFO_START", msg.text)
+ await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
@callback("pmfs", owner=True)
@@ -1154,7 +1112,7 @@ async def heheh(event):
err = ""
async with event.client.conversation(event.chat_id) as conv:
await conv.send_message(
- "• Send The Chat Id(s), which you want user to Join Before using Chat/Pm Bot"
+ "• Send The Chat Id(s), which you want user to Join Before using Chat/Pm Bot\n\n• Send /clear to disable PmBot Force sub..\n• • Send /cancel to stop this process.."
)
await conv.send_message(
"Example : \n`-1001234567\n-100778888`\n\nFor Multiple Chat(s)."
@@ -1162,10 +1120,14 @@ async def heheh(event):
try:
msg = await conv.get_response()
except AsyncTimeOut:
- return await conv.send_message("TimeUp!\nStart from /start back.")
+ return await conv.send_message("**• TimeUp!**\nStart from /start back.")
if not msg.text or msg.text.startswith("/"):
+ timyork = "Cancelled!"
+ if msg.text == "/clear":
+ udB.del_key("PMBOT_FSUB")
+ timyork = "Done! Force Subscribe Stopped\nRestart your Bot!"
return await conv.send_message(
- "Cancelled!", buttons=get_back_button("chatbot")
+ "Cancelled!", buttons=get_back_button("cbs_chatbot")
)
for chat in msg.message.split("\n"):
if chat.startswith("-") or chat.isdigit():
@@ -1177,9 +1139,9 @@ async def heheh(event):
err += f"**{chat}** : {er}\n"
if err:
return await conv.send_message(err)
- udB.set("PMBOT_FSUB", str(Ll))
+ udB.set_key("PMBOT_FSUB", str(Ll))
await conv.send_message(
- "Done!\nRestart Your Bot.", buttons=get_back_button("chatbot")
+ "Done!\nRestart Your Bot.", buttons=get_back_button("cbs_chatbot")
)
@@ -1199,7 +1161,7 @@ async def name(event):
if themssg == "/cancel":
return await conv.send_message(
"Cancelled!!",
- buttons=get_back_button("chatbot"),
+ buttons=get_back_button("cbs_chatbot"),
)
await setit(event, var, themssg)
await conv.send_message(
@@ -1207,7 +1169,7 @@ async def name(event):
name,
themssg,
),
- buttons=get_back_button("chatbot"),
+ buttons=get_back_button("cbs_chatbot"),
)
@@ -1223,7 +1185,7 @@ async def chon(event):
event.client.add_event_handler(i, events.NewMessage(**e))
await event.edit(
"Done! Now u Can Chat With People Via This Bot",
- buttons=[Button.inline("« Bᴀᴄᴋ", data="chatbot")],
+ buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
)
@@ -1236,50 +1198,10 @@ async def chon(event):
event.client.remove_event_handler(i)
await event.edit(
"Done! Chat People Via This Bot Stopped.",
- buttons=[Button.inline("« Bᴀᴄᴋ", data="chatbot")],
+ buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")],
)
-@callback("vcb", owner=True)
-async def vcb(event):
- await event.edit(
- "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)",
- buttons=[
- [Button.inline("VC Sᴇssɪᴏɴ", data="vcs")],
- [Button.inline("« Bᴀᴄᴋ", data="setter")],
- ],
- link_preview=False,
- )
-
-
-@callback("vcs", owner=True)
-async def name(event):
- await event.delete()
- pru = event.sender_id
- var = "VC_SESSION"
- name = "VC SESSION"
- async with event.client.conversation(pru) as conv:
- await conv.send_message(
- "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.",
- )
- response = conv.wait_event(events.NewMessage(chats=pru))
- response = await response
- themssg = response.message.message
- if themssg == "/cancel":
- return await conv.send_message(
- "Cancelled!!",
- buttons=get_back_button("vcb"),
- )
- await setit(event, var, themssg)
- await conv.send_message(
- "{} changed to {}\n\nAfter Setting All Things Do restart".format(
- name,
- themssg,
- ),
- buttons=get_back_button("vcb"),
- )
-
-
@callback("inli_pic", owner=True)
async def media(event):
await event.delete()
@@ -1322,3 +1244,65 @@ async def media(event):
f"{name} has been set.",
buttons=get_back_button("setter"),
)
+
+
+FD_MEDIA = {}
+
+
+@callback(re.compile("fd(.*)"), owner=True)
+async def fdroid_dler(event):
+ uri = event.data_match.group(1).decode("utf-8")
+ if FD_MEDIA.get(uri):
+ return await event.edit(file=FD_MEDIA[uri])
+ await event.answer("• Starting Download •", alert=True)
+ await event.edit("• Downloading.. •")
+ URL = f"https://f-droid.org/packages/{uri}"
+ conte = await async_searcher(URL, re_content=True)
+ BSC = bs(conte, "html.parser", from_encoding="utf-8")
+ dl_ = BSC.find("p", "package-version-download").find("a")["href"]
+ title = BSC.find("h3", "package-name").text.strip()
+ thumb = BSC.find("img", "package-icon")["src"]
+ if thumb.startswith("/"):
+ thumb = "https://f-droid.org" + thumb
+ thumb, _ = await fast_download(thumb, filename=uri + ".png")
+ s_time = time.time()
+ file, _ = await fast_download(
+ dl_,
+ filename=title + ".apk",
+ progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
+ progress(
+ d,
+ t,
+ event,
+ s_time,
+ "Downloading...",
+ )
+ ),
+ )
+ tt = time.time()
+ n_file = await uploader(file, file, tt, event, "Uploading...")
+ buttons = Button.switch_inline("Search Back", query="fdroid", same_peer=True)
+ try:
+ msg = await event.edit(
+ f"**• [{title}]({URL}) •**", file=n_file, thumb=thumb, buttons=buttons
+ )
+ except Exception as er:
+ LOGS.exception(er)
+ try:
+ msg = await event.client.edit_message(
+ await event.get_input_chat(),
+ event.message_id,
+ f"**• [{title}]({URL}) •**",
+ buttons=buttons,
+ thumb=thumb,
+ file=n_file,
+ )
+ except Exception as er:
+ os.remove(thumb)
+ os.remove(file)
+ LOGS.exception(er)
+ return await event.edit(f"**ERROR**: `{er}`", buttons=buttons)
+ if msg and hasattr(msg, "media"):
+ FD_MEDIA.update({uri: msg.media})
+ os.remove(thumb)
+ os.remove(file)
diff --git a/assistant/games.py b/assistant/games.py
new file mode 100644
index 0000000000000000000000000000000000000000..44cc823e42de67a4ded367d345726fa1356d7e00
--- /dev/null
+++ b/assistant/games.py
@@ -0,0 +1,308 @@
+# Ultroid - UserBot
+# Copyright (C) 2021-2022 TeamUltroid
+#
+# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
+# PLease read the GNU Affero General Public License in
+# .
+
+"""
+• `{i}akinator` | `/akinator`
+ Start akinator game from Userbot/Assistant
+
+• `/startgame`
+ Open Portal for Games
+"""
+
+import asyncio
+import operator
+import re
+import uuid
+from html import unescape
+from random import choice, shuffle
+
+import akinator
+from pyUltroid.functions.helper import inline_mention
+from pyUltroid.functions.tools import async_searcher
+from pyUltroid.misc._decorators import ultroid_cmd
+from telethon.errors.rpcerrorlist import (
+ BotMethodInvalidError,
+ ChatSendStickersForbiddenError,
+)
+from telethon.events import Raw
+from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
+
+from . import *
+
+# -------------------------- Akinator ----------------------- #
+
+games = {}
+aki_photo = "https://telegra.ph/file/3cc8825c029fd0cab9edc.jpg"
+
+
+@ultroid_cmd(pattern="akinator")
+async def akina(e):
+ sta = akinator.Akinator()
+ games.update({e.chat_id: {e.id: sta}})
+ try:
+ m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}")
+ await m[0].click(e.chat_id)
+ except BotMethodInvalidError:
+ await asst.send_file(
+ e.chat_id,
+ aki_photo,
+ buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"),
+ )
+ except Exception as er:
+ return await e.eor(f"**ERROR :** `{er}`")
+ if e.out:
+ await e.delete()
+
+
+@asst_cmd(pattern="akinator", owner=True)
+async def _akokk(e):
+ await akina(e)
+
+
+@callback(re.compile("aki_(.*)"), owner=True)
+async def doai(e):
+ adt = e.pattern_match.group(1).decode("utf-8")
+ dt = adt.split("_")
+ ch = int(dt[0])
+ mid = int(dt[1])
+ await e.edit(get_string("com_1"))
+ try:
+ qu = games[ch][mid].start_game(child_mode=True)
+ # child mode should be promoted
+ except KeyError:
+ return await e.answer(get_string("aki_1"), alert=True)
+ bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]]
+ cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]]
+
+ bts = [bts, cts]
+ # ignored Back Button since it makes the Pagination looks Bad
+ await e.edit("Q. " + qu, buttons=bts)
+
+
+@callback(re.compile("aka_(.*)"), owner=True)
+async def okah(e):
+ mk = e.pattern_match.group(1).decode("utf-8").split("_")
+ ch = int(mk[0])
+ mid = int(mk[1])
+ ans = mk[2]
+ try:
+ gm = games[ch][mid]
+ except KeyError:
+ await e.answer(get_string("aki_3"))
+ return
+ text = gm.answer(ans)
+ if gm.progression >= 80:
+ gm.win()
+ gs = gm.first_guess
+ text = "It's " + gs["name"] + "\n " + gs["description"]
+ return await e.edit(text, file=gs["absolute_picture_path"])
+ bts = [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]]
+ cts = [
+ Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]
+ ]
+
+ bts = [bts, cts]
+ await e.edit(text, buttons=bts)
+
+
+@in_pattern(re.compile("aki_?(.*)"), owner=True)
+async def eiagx(e):
+ bts = Button.inline(get_string("aki_2"), data=e.text)
+ ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", [])
+ ans = [
+ await e.builder.article(
+ "Akinator",
+ type="photo",
+ content=ci,
+ text="Akinator",
+ thumb=ci,
+ buttons=bts,
+ include_media=True,
+ )
+ ]
+ await e.answer(ans)
+
+
+# ----------------------- Main Command ------------------- #
+
+
+@asst_cmd(pattern="startgame", owner=True)
+async def magic(event):
+ buttons = [
+ [Button.inline("Trivia Quiz", "trzia")],
+ [Button.inline("Cancel ❌", "delit")],
+ ]
+ await event.reply(
+ get_string("games_1"),
+ file="https://telegra.ph/file/1c51015bae5205a65fd69.jpg",
+ buttons=buttons,
+ )
+
+
+# -------------------------- Trivia ----------------------- #
+
+TR_BTS = {}
+DIFI_KEYS = ["Easy", "Medium", "Hard"]
+TRIVIA_CHATS = {}
+POLLS = {}
+CONGO_STICKER = [
+ "CAADAgADSgIAAladvQrJasZoYBh68AI",
+ "CAADAgADXhIAAuyZKUl879mlR_dkOwI",
+ "CAADAgADpQAD9wLID-xfZCDwOI5LAg",
+ "CAADAgADjAADECECEFZM-SrKO9GgAg",
+ "CAADAgADSwIAAj-VzArAzNCDiGWAHAI",
+ "CAADAgADhQADwZxgDIuMHR9IU10iAg",
+]
+
+
+@callback("delit")
+async def delete_it(event):
+ await event.delete()
+
+
+@callback(re.compile("ctdown(.*)"), owner=True)
+async def ct_spam(e):
+ n = e.data_match.group(1).decode("utf-8")
+ await e.answer(f"Wait {n} seconds..", alert=True)
+
+
+@callback(re.compile("trzia(.*)"), owner=True)
+async def choose_cata(event):
+ match = event.data_match.group(1).decode("utf-8")
+ if not match:
+ if TR_BTS.get("category"):
+ buttons = TR_BTS["category"]
+ else:
+ req = (
+ await async_searcher(
+ "https://opentdb.com/api_category.php", re_json=True
+ )
+ )["trivia_categories"]
+ btt = []
+ for i in req:
+ name = i["name"]
+ if ":" in name:
+ name = name.split(":")[1]
+ btt.append(Button.inline(name, f"trziad_{i['id']}"))
+ buttons = list(zip(btt[::2], btt[1::2]))
+ if len(btt) % 2 == 1:
+ buttons.append((btt[-1],))
+ buttons.append([Button.inline("Cancel ❌", "delit")])
+ TR_BTS.update({"category": buttons})
+ text = get_string("games_2")
+ elif match[0] == "d":
+ cat = match[1:]
+ buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]]
+ buttons.append(get_back_button("trzia"))
+ text = get_string("games_3")
+ elif match[0] == "c":
+ m = match[1:]
+ buttons = [[Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)]]
+ text = get_string("games_4")
+ elif match[0] == "t":
+ m_ = match[1:]
+ buttons = [
+ [Button.inline(str(i), f"trzias{m_}_{i}") for i in [10, 30, 60, 120]]
+ ]
+ text = get_string("games_5")
+ elif match[0] == "s":
+ chat = event.chat_id
+ cat, le, nu, in_ = match[2:].split("_")
+ msg = await event.edit(get_string("games_6").format(le, nu))
+ for i in reversed(range(5)):
+ msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}"))
+ await asyncio.sleep(1)
+ await msg.edit(
+ msg.text + "\n\n• Send /cancel to stop the Quiz...", buttons=None
+ )
+ qsss = await async_searcher(
+ f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}",
+ re_json=True,
+ )
+ qs = qsss["results"]
+ if not qs:
+ await event.respond("Sorry, No Question Found for the given Criteria..")
+ await event.delete()
+ return
+ TRIVIA_CHATS.update({chat: {}})
+ for copper, q in enumerate(qs):
+ if TRIVIA_CHATS[chat].get("cancel") is not None:
+ break
+ ansi = str(uuid.uuid1()).split("-")[0].encode()
+ opts = [PollAnswer(unescape(q["correct_answer"]), ansi)]
+ [
+ opts.append(
+ PollAnswer(unescape(a), str(uuid.uuid1()).split("-")[0].encode())
+ )
+ for a in q["incorrect_answers"]
+ ]
+ shuffle(opts)
+ poll = InputMediaPoll(
+ Poll(
+ 0,
+ f"[{copper+1}]. " + unescape(q["question"]),
+ answers=opts,
+ public_voters=True,
+ quiz=True,
+ close_period=int(in_),
+ ),
+ correct_answers=[ansi],
+ solution="Join @TheUltroid",
+ solution_entities=[],
+ )
+ m_ = await event.client.send_message(chat, file=poll)
+ POLLS.update({m_.poll.poll.id: {"chat": m_.chat_id, "answer": ansi}})
+ await asyncio.sleep(int(in_))
+ if not TRIVIA_CHATS[chat]:
+ await event.respond(
+ "No-One Got Any Score in the Quiz!\nBetter Luck Next Time!"
+ )
+ else:
+ try:
+ await event.respond(file=choice(CONGO_STICKER))
+ except ChatSendStickersForbiddenError:
+ pass
+ LBD = "🎯 **Scoreboard of the Quiz.**\n\n"
+ TRC = TRIVIA_CHATS[chat]
+ if "cancel" in TRC.keys():
+ del TRC["cancel"]
+ for userid, user_score in dict(
+ sorted(TRC.items(), key=operator.itemgetter(1), reverse=True)
+ ).items():
+ user = inline_mention(await event.client.get_entity(userid))
+ LBD += f"••• {user} - {user_score}\n"
+ await event.respond(LBD)
+ del TRIVIA_CHATS[chat]
+ list_ = list(POLLS.copy().keys())
+ for key in list_:
+ if POLLS[key]["chat"] == chat:
+ del POLLS[key]
+ return
+ await event.edit(text, buttons=buttons)
+
+
+@asst.on(
+ Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id))
+)
+async def pollish(eve):
+ if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys():
+ return
+ if POLLS[eve.poll_id]["answer"] != eve.options[0]:
+ return
+ chat = POLLS.get(eve.poll_id)["chat"]
+ user = eve.user_id
+ if not TRIVIA_CHATS.get(chat, {}).get(user):
+ TRIVIA_CHATS[chat][user] = 1
+ else:
+ TRIVIA_CHATS[chat][user] += 1
+
+
+@asst_cmd("cancel", owner=True, func=lambda x: TRIVIA_CHATS.get(x.chat_id))
+async def cancelish(event):
+ chat = TRIVIA_CHATS.get(event.chat_id)
+ chat.update({"cancel": True})
+ await event.respond("Cancelled!")
diff --git a/assistant/initial.py b/assistant/initial.py
index dbb0f4fe8a9b658a85a82b890a58b5f3bbcdca90..9e1e55b4c092c988ca4e4b45614e804553291df2 100644
--- a/assistant/initial.py
+++ b/assistant/initial.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
diff --git a/assistant/inlinestuff.py b/assistant/inlinestuff.py
index 9c85bfda2540580905331081df62cabdca18fc83..0924203e4415a6367134716a43aea08c8df5e372 100644
--- a/assistant/inlinestuff.py
+++ b/assistant/inlinestuff.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -10,14 +10,21 @@ from datetime import datetime
from random import choice
from re import compile as re_compile
-import requests
from bs4 import BeautifulSoup as bs
from pyUltroid.functions.misc import google_search
-from pyUltroid.functions.tools import async_searcher, dloader, get_ofox
+from pyUltroid.functions.tools import (
+ _webupload_cache,
+ async_searcher,
+ get_ofox,
+ saavn_search,
+ webuploader,
+)
from telethon import Button
+from telethon.tl.types import DocumentAttributeAudio as Audio
from telethon.tl.types import InputWebDocument as wb
from . import *
+from . import _ult_cache
SUP_BUTTONS = [
[
@@ -30,20 +37,15 @@ ofox = "https://telegra.ph/file/231f0049fcd722824f13b.jpg"
gugirl = "https://telegra.ph/file/0df54ae4541abca96aa11.jpg"
ultpic = "https://telegra.ph/file/4136aa1650bc9d4109cc5.jpg"
-api1 = base64.b64decode("QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV").decode(
- "ascii"
-)
-api2 = base64.b64decode("QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn").decode(
- "ascii"
-)
-api3 = base64.b64decode("QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR").decode(
- "ascii"
-)
+apis = [
+ "QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV",
+ "QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn",
+ "QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR",
+]
@in_pattern("ofox", owner=True)
async def _(e):
- match = None
try:
match = e.text.split(" ", maxsplit=1)[1]
except IndexError:
@@ -101,27 +103,31 @@ async def _(e):
@in_pattern("fl2lnk ?(.*)", owner=True)
async def _(e):
- file_path = e.pattern_match.group(1)
- file_name = file_path.split("/")[-1]
- bitton = [
+ match = e.pattern_match.group(1)
+ chat_id, msg_id = match.split(":")
+ filename = _webupload_cache[int(chat_id)][int(msg_id)]
+ if "/" in filename:
+ filename = filename.split("/")[-1]
+ __cache = f"{chat_id}:{msg_id}"
+ buttons = [
[
- Button.inline("anonfiles", data=f"flanonfiles//{file_path}"),
- Button.inline("transfer", data=f"fltransfer//{file_path}"),
+ Button.inline("anonfiles", data=f"flanonfiles//{__cache}"),
+ Button.inline("transfer", data=f"fltransfer//{__cache}"),
],
[
- Button.inline("bayfiles", data=f"flbayfiles//{file_path}"),
- Button.inline("x0", data=f"flx0//{file_path}"),
+ Button.inline("bayfiles", data=f"flbayfiles//{__cache}"),
+ Button.inline("x0.at", data=f"flx0.at//{__cache}"),
],
[
- Button.inline("file.io", data=f"flfile.io//{file_path}"),
- Button.inline("siasky", data=f"flsiasky//{file_path}"),
+ Button.inline("file.io", data=f"flfile.io//{__cache}"),
+ Button.inline("siasky", data=f"flsiasky//{__cache}"),
],
]
try:
lnk = e.builder.article(
- title="fl2lnk",
- text=f"**File:**\n{file_name}",
- buttons=bitton,
+ title=f"Upload {filename}",
+ text=f"**File:**\n{filename}",
+ buttons=buttons,
)
except BaseException:
lnk = e.builder.article(
@@ -141,10 +147,13 @@ async def _(e):
t = (e.data).decode("UTF-8")
data = t[2:]
host = data.split("//")[0]
- file = data.split("//")[1]
- file_name = file.split("/")[-1]
- await e.edit(f"Uploading `{file_name}` on {host}")
- await dloader(e, host, file)
+ chat_id, msg_id = data.split("//")[1].split(":")
+ filename = _webupload_cache[int(chat_id)][int(msg_id)]
+ if "/" in filename:
+ filename = filename.split("/")[-1]
+ await e.edit(f"Uploading `{filename}` on {host}")
+ link = (await webuploader(chat_id, msg_id, host)).strip().replace("\n", "")
+ await e.edit(f"Uploaded [{filename}]({link}) on {host}.")
@in_pattern("repo", owner=True)
@@ -210,16 +219,15 @@ async def _(e):
try:
quer = e.text.split(" ", maxsplit=1)[1]
except IndexError:
- await e.answer(
+ return await e.answer(
[], switch_pm="Mod Apps Search. Enter app name!", switch_pm_param="start"
)
page = 1
start = (page - 1) * 3 + 1
- da = choice([api1, api2, api3])
+ da = base64.b64decode(choice(apis)).decode("ascii")
url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}"
- data = requests.get(url).json()
+ data = await async_searcher(url, re_json=True)
search_items = data.get("items")
- search(quer)
modss = []
for a in search_items:
title = a.get("title")
@@ -288,19 +296,23 @@ async def xda_dev(event):
APP_CACHE = {}
+RECENTS = {}
@in_pattern("app", owner=True)
async def _(e):
try:
- f = e.text.split(" ", maxsplit=1)[1]
+ f = e.text.split(" ", maxsplit=1)[1].lower()
except IndexError:
- swa = get_string("instu_1")
+ get_string("instu_1")
res = []
- if APP_CACHE:
- [res.append(APP_CACHE[a][0]) for a in APP_CACHE.keys()]
- swa = get_string("instu_2")
- return await e.answer(res, switch_pm=swa, switch_pm_param="start")
+ if APP_CACHE and RECENTS.get(e.sender_id):
+ for a in RECENTS[e.sender_id]:
+ if APP_CACHE.get(a):
+ res.append(APP_CACHE[a][0])
+ return await e.answer(
+ res, switch_pm=get_string("instu_2"), switch_pm_param="start"
+ )
try:
return await e.answer(
APP_CACHE[f], switch_pm="Application Searcher.", switch_pm_param="start"
@@ -355,6 +367,10 @@ async def _(e):
),
)
APP_CACHE.update({f: foles})
+ if RECENTS.get(e.sender_id):
+ RECENTS[e.sender_id].append(f)
+ else:
+ RECENTS.update({e.sender_id: [f]})
await e.answer(foles, switch_pm="Application Searcher.", switch_pm_param="start")
@@ -371,6 +387,9 @@ async def piston_run(event):
result = await event.builder.article(
title="Bad Query",
description="Usage: [Language] [code]",
+ thumb=wb(
+ "https://telegra.ph/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
+ ),
text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://telegra.ph/Ultroid-09-01-6)',
)
return await event.answer([result])
@@ -383,23 +402,284 @@ async def piston_run(event):
result = await event.builder.article(
title="Unsupported Language",
description="Usage: [Language] [code]",
+ thumb=wb(
+ "https://telegra.ph/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", []
+ ),
text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://telegra.ph/Ultroid-09-01-6)',
)
return await event.answer([result])
- output = (
- await async_searcher(
- PISTON_URI + "execute",
- post=True,
- json={"language": lang, "version": version, "files": [{"content": code}]},
- re_json=True,
- )
- )["run"]["output"] or get_string("instu_4")
+ output = await async_searcher(
+ PISTON_URI + "execute",
+ post=True,
+ json={"language": lang, "version": version, "files": [{"content": code}]},
+ re_json=True,
+ )
+ output = output["run"]["output"] or get_string("instu_4")
if len(output) > 3000:
output = output[:3000] + "..."
result = await event.builder.article(
title="Result",
description=output,
text=f"• **Language:**\n`{lang}`\n\n• **Code:**\n`{code}`\n\n• **Result:**\n`{output}`",
+ thumb=wb(
+ "https://telegra.ph/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", []
+ ),
buttons=Button.switch_inline("Fork", query=event.text, same_peer=True),
)
await event.answer([result], switch_pm="• Piston •", switch_pm_param="start")
+
+
+FDROID_ = {}
+
+
+@in_pattern("fdroid", owner=True)
+async def do_magic(event):
+ try:
+ match = event.text.split(" ", maxsplit=1)[1].lower()
+ except IndexError:
+ return await event.answer(
+ [], switch_pm="Enter Query to Search", switch_pm_param="start"
+ )
+ if FDROID_.get(match):
+ return await event.answer(
+ FDROID_[match], switch_pm=f"• Results for {match}", switch_pm_param="start"
+ )
+ link = "https://search.f-droid.org/?q=" + match.replace(" ", "+")
+ content = await async_searcher(link, re_content=True)
+ BSC = bs(content, "html.parser", from_encoding="utf-8")
+ ress = []
+ for dat in BSC.find_all("a", "package-header")[:10]:
+ image = dat.find("img", "package-icon")["src"]
+ if image.endswith("/"):
+ image = "https://telegra.ph/file/a8dd4a92c5a53a89d0eff.jpg"
+ title = dat.find("h4", "package-name").text.strip()
+ desc = dat.find("span", "package-summary").text.strip()
+ text = f"• **Name :** `{title}`\n\n"
+ text += f"• **Description :** `{desc}`\n"
+ text += f"• **License :** `{dat.find('span', 'package-license').text.strip()}`"
+ imga = wb(image, 0, "image/jpeg", [])
+ ress.append(
+ await event.builder.article(
+ title=title,
+ type="photo",
+ description=desc,
+ text=text,
+ content=imga,
+ thumb=imga,
+ include_media=True,
+ buttons=[
+ Button.inline(
+ "• Download •", "fd" + dat["href"].split("packages/")[-1]
+ ),
+ Button.switch_inline("• Share •", query=event.text),
+ ],
+ )
+ )
+ msg = f"Showing {len(ress)} Results!" if ress else "No Results Found"
+ FDROID_.update({match: ress})
+ await event.answer(ress, switch_pm=msg, switch_pm_param="start")
+
+
+_koo_ = {}
+
+
+@in_pattern("koo", owner=True)
+async def koo_search(ult):
+ """Search Users on koo with API"""
+ try:
+ match = ult.text.split(maxsplit=1)[1].lower()
+ match_ = match
+ except IndexError:
+ return await ult.answer(
+ [], switch_pm="Enter Query to Search..", switch_pm_param="start"
+ )
+ if _koo_.get(match):
+ return await ult.answer(
+ _koo_[match], switch_pm="• Koo Search •", switch_pm_param="start"
+ )
+ res = []
+ se_ = None
+ key_count = None
+ if " | " in match:
+ match = match.split(" | ", maxsplit=1)
+ try:
+ key_count = int(match[1])
+ except ValueError:
+ pass
+ match = match[0]
+ match = match.replace(" ", "+")
+ req = await async_searcher(
+ f"https://www.kooapp.com/apiV1/search?query={match}&searchType=EXPLORE",
+ re_json=True,
+ )
+ if key_count:
+ try:
+ se_ = [req["feed"][key_count - 1]]
+ except KeyError:
+ pass
+ if not se_:
+ se_ = req["feed"]
+ for count, feed in enumerate(se_[:10]):
+ if feed["uiItemType"] == "search_profile":
+ count += 1
+ item = feed["items"][0]
+ profileImage = (
+ item["profileImageBaseUrl"]
+ if item.get("profileImageBaseUrl")
+ else "https://telegra.ph/file/dc28e69bd7ea2c0f25329.jpg"
+ )
+ extra = await async_searcher(
+ "https://www.kooapp.com/apiV1/users/handle/" + item["userHandle"],
+ re_json=True,
+ )
+ img = wb(profileImage, 0, "image/jpeg", [])
+ text = f"‣ **Name :** `{item['name']}`"
+ if extra.get("title"):
+ text += f"\n‣ **Title :** `{extra['title']}`"
+ text += f"\n‣ **Username :** `@{item['userHandle']}`"
+ if extra.get("description"):
+ text += f"\n‣ **Description :** `{extra['description']}`"
+ text += f"\n‣ **Followers :** `{extra['followerCount']}` ‣ **Following :** {extra['followingCount']}"
+ if extra.get("socialProfile") and extra["socialProfile"].get("website"):
+ text += f"\n‣ **Website :** {extra['socialProfile']['website']}"
+ res.append(
+ await ult.builder.article(
+ title=item["name"],
+ description=item.get("title") or f"@{item['userHandle']}",
+ type="photo",
+ content=img,
+ thumb=img,
+ include_media=True,
+ text=text,
+ buttons=[
+ Button.url(
+ "View", "https://kooapp.com/profile/" + item["userHandle"]
+ ),
+ Button.switch_inline(
+ "• Share •",
+ query=ult.text if key_count else ult.text + f" | {count}",
+ ),
+ ],
+ )
+ )
+ if not res:
+ switch = "No Results Found :("
+ else:
+ _koo_.update({match_: res})
+ switch = f"Showing {len(res)} Results!"
+ await ult.answer(res, switch_pm=switch, switch_pm_param="start")
+
+
+# Thanks to OpenSource
+_bearer_collected = [
+ "AAAAAAAAAAAAAAAAAAAAALIKKgEAAAAA1DRuS%2BI7ZRKiagD6KHYmreaXomo%3DP5Vaje4UTtEkODg0fX7nCh5laSrchhtLxeyEqxXpv0w9ZKspLD",
+ "AAAAAAAAAAAAAAAAAAAAAL5iUAEAAAAAmo6FYRjqdKlI3cNziIm%2BHUQB9Xs%3DS31pj0mxARMTOk2g9dvQ1yP9wknvY4FPBPUlE00smJcncw4dPR",
+ "AAAAAAAAAAAAAAAAAAAAAN6sVgEAAAAAMMjMMWrwgGyv7YQOWN%2FSAsO5SGM%3Dg8MG9Jq93Rlllaok6eht7HvRCruN4Vpzp4NaVsZaaHHWSTzKI8",
+]
+
+
+@in_pattern("twitter", owner=True)
+async def twitter_search(event):
+ try:
+ match = event.text.split(maxsplit=1)[1].lower()
+ except IndexError:
+ return await event.answer(
+ [], switch_pm="Enter Query to Search", switch_pm_param="start"
+ )
+ try:
+ return await event.answer(
+ _ult_cache["twitter"][match],
+ switch_pm="• Twitter Search •",
+ switch_pm_param="start",
+ )
+ except KeyError:
+ pass
+ headers = {"Authorization": "bearer " + choice(_bearer_collected)}
+ res = await async_searcher(
+ f"https://api.twitter.com/1.1/users/search.json?q={match}",
+ headers=headers,
+ re_json=True,
+ )
+ reso = []
+ for user in res:
+ thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", [])
+ if user.get("profile_banner_url"):
+ url = user["profile_banner_url"]
+ text = f"[\xad]({url})• **Name :** `{user['name']}`\n"
+ else:
+ text = f"• **Name :** `{user['name']}`\n"
+ text += f"• **Description :** `{user['description']}`\n"
+ text += f"• **Username :** `@{user['screen_name']}`\n"
+ text += f"• **Followers :** `{user['followers_count']}` • **Following :** `{user['friends_count']}`\n"
+ pro_ = "https://twitter.com/" + user["screen_name"]
+ text += f"• **Link :** [Click Here]({pro_})\n_"
+ reso.append(
+ await event.builder.article(
+ title=user["name"],
+ description=user["description"],
+ url=pro_,
+ text=text,
+ thumb=thumb,
+ )
+ )
+ swi_ = "No User Found :(" if not reso else f"🐦 Showing {len(reso)} Results!"
+ await event.answer(reso, switch_pm=swi_, switch_pm_param="start")
+ if _ult_cache.get("twitter"):
+ _ult_cache["twitter"].update({match: reso})
+ else:
+ _ult_cache.update({"twitter": {match: reso}})
+
+
+_savn_cache = {}
+
+
+@in_pattern("saavn", owner=True)
+async def savn_s(event):
+ try:
+ query = event.text.split(maxsplit=1)[1].lower()
+ except IndexError:
+ return await event.answer(
+ [], switch_pm="Enter Query to search 🔍", switch_pm_param="start"
+ )
+ if query in _savn_cache:
+ return await event.answer(
+ _savn_cache[query],
+ switch_pm=f"Showing Results for {query}",
+ switch_pm_param="start",
+ )
+ results = await saavn_search(query)
+ swi = "No Results Found!" if not results else "🎵 Saavn Search"
+ res = []
+ for song in results:
+ thumb = wb(song["image"], 0, "image/jpeg", [])
+ text = f"• **Title :** {song['song']}"
+ text += f"\n• **Year :** {song['year']}"
+ text += f"\n• **Lang :** {song['language']}"
+ text += f"\n• **Artist :** {song['primary_artists']}"
+ text += f"\n• **Release Date :** {song['release_date']}"
+ res.append(
+ await event.builder.article(
+ title=song["song"],
+ type="audio",
+ text=text,
+ include_media=True,
+ buttons=Button.switch_inline(
+ "Search Again 🔍", query="saavn", same_peer=True
+ ),
+ thumb=thumb,
+ content=wb(
+ song["media_url"],
+ 0,
+ "audio/mp4",
+ [
+ Audio(
+ title=song["song"],
+ duration=int(song["duration"]),
+ performer=song["primary_artists"],
+ )
+ ],
+ ),
+ )
+ )
+ await event.answer(res, switch_pm=swi, switch_pm_param="start")
+ _savn_cache.update({query: res})
diff --git a/assistant/localization.py b/assistant/localization.py
index 0749efef26e4029ae76ea310550492f837dc0b85..b5fdd5cca58fbfe9aa4aaaddfc172c9be7513026 100644
--- a/assistant/localization.py
+++ b/assistant/localization.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -32,7 +32,7 @@ async def settt(event):
lang = event.data_match.group(1).decode("UTF-8")
languages = get_languages()
language[0] = lang
- udB.delete("language") if lang == "en" else udB.set("language", lang)
+ udB.del_key("language") if lang == "en" else udB.set_key("language", lang)
await event.edit(
f"Your language has been set to {languages[lang]['natively']} [{lang}].",
buttons=get_back_button("lang"),
diff --git a/assistant/manager/__init__.py b/assistant/manager/__init__.py
index 49ec5ba7ca8ba7832cb41b2726e2cf17d642933a..02ba8443ee63b66a893654e853f1b359f440c3b9 100644
--- a/assistant/manager/__init__.py
+++ b/assistant/manager/__init__.py
@@ -1,10 +1,11 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
-from .. import *
-from pyUltroid.misc._decorators import ultroid_cmd
from pyUltroid.functions.helper import inline_mention
+from pyUltroid.misc._decorators import ultroid_cmd
+
+from .. import *
diff --git a/assistant/manager/_help.py b/assistant/manager/_help.py
index 9be19498934a9b575b225c50240d66200c7b06d9..3c127df7246b8e54bc8ced52d0f54b936d7adaa5 100644
--- a/assistant/manager/_help.py
+++ b/assistant/manager/_help.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -44,6 +44,7 @@ UTILITIES = """
• /info (reply/username/id) : get detailed info of user.
• /id : get chat/user id.
• /tr : Translate Languages..
+• /q : Create Quotes.
• /paste (reply file/text) : paste content on Spaceb.in
• /meaning (text) : Get Meaning of that Word.
@@ -75,11 +76,15 @@ MISC = """
• /joke : Get Random Jokes.
• /decide : Decide Something..
+
+**✘ Stickertools ✘**
+• /kang : add sticker to your pack.
+• /listpack : get all of yours pack..
"""
STRINGS = {"Admintools": ADMINTOOLS, "locks": LOCKS, "Utils": UTILITIES, "Misc": MISC}
-MNGE = udB.get("MNGR_EMOJI") or "•"
+MNGE = udB.get_key("MNGR_EMOJI") or "•"
def get_buttons():
@@ -105,11 +110,10 @@ async def helpish(event):
"Contact me in PM for help!", buttons=Button.url("Click me for Help", url)
)
if str(event.sender_id) in owner_and_sudos() and (
- udB.get("DUAL_MODE") and (udB.get("DUAL_HNDLR") == "/")
+ udB.get_key("DUAL_MODE") and (udB.get_key("DUAL_HNDLR") == "/")
):
return
- BTTS = get_buttons()
- await event.reply(START, buttons=BTTS)
+ await event.reply(START, buttons=get_buttons())
@callback("mngbtn", owner=True)
diff --git a/assistant/manager/_on_adds.py b/assistant/manager/_on_adds.py
index 2be0babf4a10146e2221ae233d15f3684a1ec51a..a68f72f28533d69502c29ddabf51a0653759bf85 100644
--- a/assistant/manager/_on_adds.py
+++ b/assistant/manager/_on_adds.py
@@ -1,20 +1,21 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
-from . import *
from telethon import events
+from . import *
+
-@asst.on(events.ChatAction(func= lambda x: x.user_added))
+@asst.on(events.ChatAction(func=lambda x: x.user_added))
async def dueha(e):
user = await e.get_user()
if not user.is_self:
return
- sm = udB.get("ON_MNGR_ADD")
+ sm = udB.get_key("ON_MNGR_ADD")
if sm == "OFF":
return
if not sm:
diff --git a/assistant/manager/admins.py b/assistant/manager/admins.py
index 35b9245186a418fedd7f462a7d08ef572521d728..c9a2dbdff961c63b4de375c3c432a922e03b7556 100644
--- a/assistant/manager/admins.py
+++ b/assistant/manager/admins.py
@@ -1,38 +1,49 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
+import re
+
+from pyUltroid import _ult_cache
+from telethon.errors.rpcerrorlist import UserNotParticipantError
+
from . import *
-@ultroid_cmd(pattern="dkick", type=["manager", "official"])
+@ultroid_cmd(pattern="d(kick|ban)", manager=True, require="ban_users")
async def dowj(e):
replied = await e.get_reply_message()
if replied:
user = replied.sender_id
else:
- return await eor(e, "Reply to a message...")
+ return await e.eor("Reply to a message...")
try:
await replied.delete()
- await e.client.kick_participant(e.chat_id, user)
- await eor(e, "Kicked Successfully!")
+ if e.pattern_match.group(1) == "kick":
+ await e.client.kick_participant(e.chat_id, user)
+ te = "Kicked"
+ else:
+ await e.client.edit_permissions(e.chat_id, user, view_messages=False)
+ te = "Banned"
+ await e.eor(f"{te} Successfully!")
except Exception as E:
- await eor(e, str(E))
+ await e.eor(str(E))
-@ultroid_cmd(pattern="dban", type=["manager", "official"])
-async def dowj(e):
- replied = await e.get_reply_message()
- if replied:
- user = replied.sender_id
- else:
- return await eor(e, "Reply to a message...")
+@callback(re.compile("cc_(.*)"), func=_ult_cache.get("admin_callback"))
+async def callback_(event):
+ data = event.data_match.group(1).decode("utf-8")
+ if data not in _ult_cache.get("admin_callback", {}):
+ return
try:
- await replied.delete()
- await e.client.edit_permissions(e.chat_id, user, view_messages=False)
- await eor(e, "Banned Successfully!")
- except Exception as E:
- await eor(e, str(E))
+ perm = await event.client.get_permissions(event.chat_id, event.sender_id)
+ except UserNotParticipantError:
+ return await event.answer("Join the Group First!", alert=True)
+ if not perm.is_admin:
+ return await event.answer("You are not an Admin!", alert=True)
+ _ult_cache["admin_callback"].update({data: (event.sender, perm)})
+ await event.answer("Verification Done!")
+ await event.delete()
diff --git a/assistant/manager/afk.py b/assistant/manager/afk.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb17160ced5df78765471d5eec87a8611f79a6ac
--- /dev/null
+++ b/assistant/manager/afk.py
@@ -0,0 +1,109 @@
+# Ultroid - UserBot
+# Copyright (C) 2021-2022 TeamUltroid
+#
+# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
+# PLease read the GNU Affero General Public License in
+# .
+
+from datetime import datetime as dt
+
+from pyUltroid.functions.helper import inline_mention, time_formatter
+from telethon.events import NewMessage
+from telethon.tl.types import (
+ Message,
+ MessageEntityMention,
+ MessageEntityMentionName,
+ User,
+)
+from telethon.utils import get_display_name
+
+from . import asst, asst_cmd
+
+AFK = {}
+
+
+@asst_cmd(pattern="afk", func=lambda x: not x.is_private)
+async def go_afk(event):
+ sender = await event.get_sender()
+ if (not isinstance(sender, User)) or sender.bot:
+ return
+ try:
+ reason = event.text.split(" ", maxsplit=1)[1]
+ except IndexError:
+ reason = None
+ if event.is_reply and not reason:
+ replied = await event.get_reply_message()
+ if not reason and replied.text and not replied.media:
+ reason = replied.text
+ else:
+ reason = replied
+ time_ = dt.now()
+ if AFK.get(event.chat_id):
+ AFK[event.chat_id].update({event.sender_id: {"reason": reason, "time": time_}})
+ else:
+ AFK.update(
+ {event.chat_id: {event.sender_id: {"reason": reason, "time": time_}}}
+ )
+ mention = inline_mention(sender)
+ msg = f"**{mention} went AFK Now!**"
+ if reason and not isinstance(reason, str):
+ await event.reply(reason)
+ else:
+ msg += f"\n\n**Reason : ** `{reason}`"
+ await event.reply(msg)
+
+
+@asst.on(NewMessage(func=lambda x: AFK.get(x.chat_id) and not x.is_private))
+async def make_change(event):
+ if event.text.startswith("/afk"):
+ return
+ sender = await event.get_sender()
+ if (not isinstance(sender, User)) or sender.bot:
+ return
+ chat_ = AFK[event.chat_id]
+ if event.sender_id in chat_.keys():
+ name = get_display_name(event.sender)
+ cha_send = chat_[event.sender_id]
+ time_ = time_formatter((dt.now() - cha_send["time"]).seconds * 1000)
+ msg = f"**{name}** is No Longer AFK!\n**Was AFK for** {time_}"
+ await event.reply(msg)
+ del chat_[event.sender_id]
+ if not chat_:
+ del AFK[event.chat_id]
+ ST_SPAM = []
+ replied = await event.get_reply_message()
+ if replied:
+ name = get_display_name(replied.sender)
+ if replied.sender_id in chat_.keys():
+ s_der = chat_[replied.sender_id]
+ res_ = s_der["reason"]
+ time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000)
+ msg = f"**{name}** is AFK Currently!\n**From :** {time_}"
+ if res_ and isinstance(res_, str):
+ msg += f"\n**Reason :** {res_}"
+ elif res_ and isinstance(res_, Message):
+ await event.reply(res_)
+ await event.reply(msg)
+ ST_SPAM.append(replied.sender_id)
+ for ent, text in event.get_entities_text():
+ dont_send, entity = None, None
+ if isinstance(ent, MessageEntityMentionName):
+ c_id = ent.user_id
+ elif isinstance(ent, MessageEntityMention):
+ c_id = text
+ else:
+ c_id = None
+ if c_id:
+ entity = await event.client.get_entity(c_id)
+ if entity and entity.id in chat_.keys() and entity.id not in ST_SPAM:
+ ST_SPAM.append(entity.id)
+ s_der = chat_[entity.id]
+ name = get_display_name(entity)
+ res_ = s_der["reason"]
+ time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000)
+ msg = f"**{name}** is AFK Currently!\n**From :** {time_}"
+ if res_ and isinstance(res_, str):
+ msg += f"\n**Reason :** {res_}"
+ elif res_ and isinstance(res_, Message):
+ await event.reply(res_)
+ await event.reply(msg)
diff --git a/assistant/manager/misc.py b/assistant/manager/misc.py
index 35ba54fc029a40456240d26b4cbd0d41935c07ee..24a44a5b7670e02cd3918df64fdf6322843da0d3 100644
--- a/assistant/manager/misc.py
+++ b/assistant/manager/misc.py
@@ -1,27 +1,28 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
-import aiohttp
import random
+
+import aiohttp
from pyUltroid.dB import DEVLIST
+
from . import *
-@ultroid_cmd(pattern="decide", type="manager")
+@asst_cmd(pattern="decide")
async def dheh(e):
text = ["Yes", "NoU", "Maybe", "IDK"]
text = random.choice(text)
- ri = e.id
- if e.is_reply:
- ri = e.reply_to_msg_id
+ ri = e.reply_to_msg_id or e.id
await e.client.send_message(e.chat_id, text, reply_to=ri)
-@ultroid_cmd(pattern="echo ?(.*)", type=["manager"])
+
+@asst_cmd(pattern="echo ?(.*)")
async def oqha(e):
match = e.pattern_match.group(1)
if match:
@@ -31,22 +32,26 @@ async def oqha(e):
text = (await e.get_reply_message()).text
reply_to = e.reply_to_msg_id
else:
- return await eor(e, "What to Echo?", time=5)
+ return await e.eor("What to Echo?", time=5)
+ try:
+ await e.delete()
+ except BaseException as ex:
+ LOGS.error(ex)
await e.client.send_message(e.chat_id, text, reply_to=reply_to)
-@ultroid_cmd(pattern="kickme$", type=["manager"], allow_all=True)
+@asst_cmd(pattern="kickme$")
async def doit(e):
if e.sender_id in DEVLIST:
return await eod(e, "`I will Not Kick You, my Developer..`")
try:
await e.client.kick_participant(e.chat_id, e.sender_id)
except Exception as Fe:
- return await eor(e, str(Fe), time=5)
- await eor(e, "Yes, You are right, get out.", time=5)
+ return await e.eor(str(Fe), time=5)
+ await e.eor("Yes, You are right, get out.", time=5)
-@ultroid_cmd(pattern="joke$", type=["manager"])
+@asst_cmd(pattern="joke$")
async def do_joke(e):
e = await e.get_reply_message() if e.is_reply else e
link = "https://v2.jokeapi.dev/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&type=single"
diff --git a/assistant/manager/stickermanager.py b/assistant/manager/stickermanager.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e7f3d8885b43eaab30a9572ebb73f14c2d70c27
--- /dev/null
+++ b/assistant/manager/stickermanager.py
@@ -0,0 +1,166 @@
+# Ultroid - UserBot
+# Copyright (C) 2021-2022 TeamUltroid
+#
+# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
+# PLease read the GNU Affero General Public License in
+# .
+
+import random
+
+from pyUltroid.functions.misc import create_quotly
+from pyUltroid.functions.tools import resize_photo
+from telethon import errors
+from telethon.errors.rpcerrorlist import StickersetInvalidError
+from telethon.tl.functions.messages import GetStickerSetRequest as GetSticker
+from telethon.tl.functions.messages import UploadMediaRequest
+from telethon.tl.functions.stickers import AddStickerToSetRequest as AddSticker
+from telethon.tl.functions.stickers import CreateStickerSetRequest
+from telethon.tl.types import InputPeerSelf
+from telethon.tl.types import InputStickerSetItem as SetItem
+from telethon.tl.types import InputStickerSetShortName, User
+from telethon.utils import get_display_name, get_input_document
+
+from . import LOGS, asst, asst_cmd, udB
+
+
+@asst_cmd(
+ pattern="kang",
+)
+async def kang_cmd(ult):
+ sender = await ult.get_sender()
+ if not isinstance(sender, User):
+ return
+ if not ult.is_reply:
+ return await ult.eor("`Reply to a sticker/photo..`", time=5)
+ reply = await ult.get_reply_message()
+ if sender.username:
+ pre = sender.username[:4]
+ else:
+ pre = random.random_string(length=3)
+ animated, dl = None, None
+ try:
+ emoji = ult.text.split(maxsplit=1)[1]
+ except IndexError:
+ emoji = None
+ if reply.sticker:
+ file = get_input_document(reply.sticker)
+ emoji = emoji or reply.file.emoji
+ if reply.file.name.endswith(".tgs"):
+ animated = True
+ dl = await reply.download_media()
+ elif reply.photo:
+ dl = await reply.download_media()
+ name = "sticker.webp"
+ image = resize_photo(dl)
+ image.save(name, "WEBP")
+ elif reply.text:
+ dl = await create_quotly(reply)
+ else:
+ return await ult.eor("`Reply to sticker or text to add it in your pack...`")
+ if not emoji:
+ emoji = "🏵"
+ if dl:
+ upl = await ult.client.upload_file(dl)
+ file = get_input_document(
+ await ult.client(UploadMediaRequest(InputPeerSelf(), upl))
+ )
+ get_ = udB.get_key("STICKERS") or {}
+ type_ = "static" if not animated else "anim"
+ if not get_.get(ult.sender_id) or not get_.get(ult.sender_id, {}).get(type_):
+ sn = f"{pre}_{ult.sender_id}"
+ title = f"{get_display_name(sender)}'s Kang Pack"
+ if animated:
+ type_ = "anim"
+ sn += "_anim"
+ title += " (Animated)"
+ sn += f"_by_{asst.me.username}"
+ try:
+ await asst(GetSticker(InputStickerSetShortName(sn), hash=0))
+ sn = sn.replace(str(ult.sender_id), f"{ult.sender_id}_{ult.id}")
+ except StickersetInvalidError:
+ pass
+ try:
+ pack = await ult.client(
+ CreateStickerSetRequest(
+ user_id=sender.id,
+ title=title,
+ short_name=sn,
+ stickers=[SetItem(file, emoji=emoji)],
+ animated=animated,
+ )
+ )
+ except Exception as er:
+ return await ult.eor(str(er))
+ sn = pack.set.short_name
+ if not get_.get(ult.sender_id):
+ get_.update({ult.sender_id: {type_: [sn]}})
+ else:
+ get_[ult.sender_id].update({type_: [sn]})
+ udB.set_key("STICKERS", get_)
+ return await ult.reply(
+ f"**Kanged Successfully!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})"
+ )
+ name = get_[ult.sender_id][type_][-1]
+ try:
+ await asst(GetSticker(InputStickerSetShortName(name), hash=0))
+ except StickersetInvalidError:
+ get_[ult.sender_id][type_].remove(name)
+ try:
+ await asst(
+ AddSticker(InputStickerSetShortName(name), SetItem(file, emoji=emoji))
+ )
+ except (errors.StickerpackStickersTooMuchError, errors.StickersTooMuchError):
+ sn = f"{pre}{ult.sender_id}_{ult.id}"
+ title = f"{get_display_name(sender)}'s Kang Pack"
+ if animated:
+ sn += "_anim"
+ title += " (Animated)"
+ sn += f"_by_{asst.me.username}"
+ try:
+ pack = await ult.client(
+ CreateStickerSetRequest(
+ user_id=sender.id,
+ title=title,
+ short_name=sn,
+ stickers=[SetItem(file, emoji=emoji)],
+ animated=animated,
+ )
+ )
+ except Exception as er:
+ return await ult.eor(str(er))
+ get_[ult.sender_id][type_].append(pack.set.short_name)
+ udB.set_key("STICKERS", get_)
+ return await ult.reply(
+ f"**Created New Kang Pack!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})"
+ )
+ except Exception as er:
+ LOGS.exception(er)
+ return await ult.reply(str(er))
+ await ult.reply(
+ f"Sticker Added to Pack Successfully\n**Link :** [Click Here](https://t.me/addstickers/{name})"
+ )
+
+
+@asst_cmd(pattern="listpack")
+async def do_magic(ult):
+ ko = udB.get_key("STICKERS") or {}
+ if not ko.get(ult.sender_id):
+ return await ult.reply("No Sticker Pack Found!")
+ al_ = []
+ ul = ko[ult.sender_id]
+ if ul.get("static"):
+ al_.extend(ul["static"])
+ if ul.get("anim"):
+ al_.extend(ul["anim"])
+ msg = "• **Stickers Owned by You!**\n\n"
+ for _ in al_:
+ try:
+ pack = await ult.client(GetSticker(InputStickerSetShortName(_), hash=0))
+ msg += f"• [{pack.set.title}](https://t.me/addstickers/{_})\n"
+ except StickerSetInvalidError:
+ if ul.get("anim") and _ in ul["anim"]:
+ ul["anim"].remove(_)
+ else:
+ ul["static"].remove(_)
+ udB.set_key("STICKERS", ko)
+ await ult.reply(msg)
diff --git a/assistant/pmbot.py b/assistant/pmbot.py
index f6b34c28448ba07fd51fde77bde9d9d4ea570cc9..425fafd4287907770451d773255f11b44709bb73 100644
--- a/assistant/pmbot.py
+++ b/assistant/pmbot.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -9,10 +9,11 @@
# --------------------------------------- Imports -------------------------------------------- #
+import os
+
from pyUltroid.dB.asst_fns import *
from pyUltroid.dB.botchat_db import *
from pyUltroid.functions.helper import inline_mention
-from pyUltroid.misc import owner_and_sudos
from telethon.errors.rpcerrorlist import UserNotParticipantError
from telethon.tl.custom import Button
from telethon.tl.functions.channels import GetFullChannelRequest
@@ -22,16 +23,18 @@ from telethon.utils import get_display_name
from . import *
-FSUB = udB.get_redis("PMBOT_FSUB")
+FSUB = udB.get_key("PMBOT_FSUB")
CACHE = {}
# --------------------------------------- Incoming -------------------------------------------- #
-@asst_cmd(load=AST_PLUGINS, incoming=True, func=lambda e: e.is_private)
+@asst_cmd(
+ load=AST_PLUGINS,
+ incoming=True,
+ func=lambda e: e.is_private and not is_blacklisted(e.sender_id),
+)
async def on_new_mssg(event):
who = event.sender_id
- if is_blacklisted(who):
- return
# doesn't reply to that user anymore
if event.text.startswith("/") or who == OWNER_ID:
return
@@ -43,7 +46,7 @@ async def on_new_mssg(event):
await event.client.get_permissions(chat, event.sender_id)
except UserNotParticipantError:
if not MSG:
- MSG += "**You need to Join Below Chat(s) in order to Chat to my Master!\n\n**"
+ MSG += get_string("pmbot_1")
try:
TAHC_ = await event.client.get_entity(chat)
if hasattr(TAHC_, "username") and TAHC_.username:
@@ -81,16 +84,21 @@ async def on_new_mssg(event):
func=lambda e: e.is_private and e.is_reply,
)
async def on_out_mssg(event):
- x = await event.get_reply_message()
- to_user = get_who(x.id)
+ x = event.reply_to_msg_id
+ to_user = get_who(x)
if event.text.startswith("/who"):
try:
k = await asst.get_entity(to_user)
- return await event.reply(
- f"• **Name :** {get_display_name(k)}\n• **ID :** `{k.id}`\n• **Link :** {inline_mention(k)}"
+ photu = await event.client.download_profile_photo(k.id)
+ await event.reply(
+ f"• **Name :** {get_display_name(k)}\n• **ID :** `{k.id}`\n• **Link :** {inline_mention(k)}",
+ file=photu,
)
- except BaseException:
+ if photu:
+ os.remove(photu)
return
+ except BaseException as er:
+ return await event.reply("**ERROR : **" + str(er))
elif event.text.startswith("/"):
return
if to_user:
@@ -103,42 +111,37 @@ async def on_out_mssg(event):
@asst_cmd(
pattern="ban",
load=AST_PLUGINS,
- from_users=owner_and_sudos(castint=True),
+ from_users=[OWNER_ID],
func=lambda x: x.is_private,
)
async def banhammer(event):
- x = await event.get_reply_message()
- if not x:
- return await event.reply("Please reply to someone to ban him.")
- target = get_who(x.id)
+ if not event.is_reply:
+ return await event.reply(get_string("pmbot_2"))
+ target = get_who(event.reply_to_msg_id)
if is_blacklisted(target):
- return await event.reply("User is already banned!")
+ return await event.reply(get_string("pmbot_3"))
blacklist_user(target)
await event.reply(f"#BAN\nUser : {target}")
- await asst.send_message(
- target,
- "`GoodBye! You have been banned.`\n**Further messages you send will not be forwarded.**",
- )
+ await asst.send_message(target, get_string("pmbot_4"))
@asst_cmd(
pattern="unban",
load=AST_PLUGINS,
- from_users=owner_and_sudos(castint=True),
+ from_users=[OWNER_ID],
func=lambda x: x.is_private,
)
async def unbanhammer(event):
- x = await event.get_reply_message()
- if not x:
- return await event.reply("Please reply to someone to Unban him.")
- target = get_who(x.id)
+ if not event.is_reply:
+ return await event.reply(get_string("pmbot_5"))
+ target = get_who(event.reply_to_msg_id)
if not is_blacklisted(target):
- return await event.reply("User was never banned!")
+ return await event.reply(get_string("pmbot_6"))
rem_blacklist(target)
await event.reply(f"#UNBAN\nUser : {target}")
- await asst.send_message(target, "`Congrats! You have been unbanned.`")
+ await asst.send_message(target, get_string("pmbot_7"))
# --------------------------------------- END -------------------------------------------- #
diff --git a/assistant/start.py b/assistant/start.py
index cf43ef0acb5662a3a18de173bc4c65bda983f7b9..65d4650659f0587f50780d6c58efd0e0ab3c7097 100644
--- a/assistant/start.py
+++ b/assistant/start.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -9,9 +9,8 @@ from datetime import datetime
from pytz import timezone as tz
from pyUltroid.dB.asst_fns import *
-from pyUltroid.dB.sudos import is_fullsudo
from pyUltroid.functions.helper import inline_mention
-from pyUltroid.misc import owner_and_sudos
+from pyUltroid.misc import SUDO_M, owner_and_sudos
from telethon import Button, events
from telethon.utils import get_display_name
@@ -19,30 +18,32 @@ from strings.strings import get_string
from . import *
-Owner_info_msg = (
- udB.get("BOT_INFO_START")
- or f"""
+Owner_info_msg = udB.get_key("BOT_INFO_START")
+custom_info = True
+if Owner_info_msg is None:
+ custom_info = False
+ Owner_info_msg = f"""
**Owner** - {OWNER_NAME}
**OwnerID** - `{OWNER_ID}`
-**Message Forwards** - {udB.get("PMBOT")}
+**Message Forwards** - {udB.get_key("PMBOT")}
**Ultroid [v{ultroid_version}](https://github.com/TeamUltroid/Ultroid), powered by @TeamUltroid**
"""
-)
+
_settings = [
[
- Button.inline("API Kᴇʏs", data="apiset"),
- Button.inline("Pᴍ Bᴏᴛ", data="chatbot"),
+ Button.inline("API Kᴇʏs", data="cbs_apiset"),
+ Button.inline("Pᴍ Bᴏᴛ", data="cbs_chatbot"),
],
[
- Button.inline("Aʟɪᴠᴇ", data="alvcstm"),
- Button.inline("PᴍPᴇʀᴍɪᴛ", data="ppmset"),
+ Button.inline("Aʟɪᴠᴇ", data="cbs_alvcstm"),
+ Button.inline("PᴍPᴇʀᴍɪᴛ", data="cbs_ppmset"),
],
[
- Button.inline("Fᴇᴀᴛᴜʀᴇs", data="otvars"),
- Button.inline("VC Sᴏɴɢ Bᴏᴛ", data="vcb"),
+ Button.inline("Fᴇᴀᴛᴜʀᴇs", data="cbs_otvars"),
+ Button.inline("VC Sᴏɴɢ Bᴏᴛ", data="cbs_vcb"),
],
[Button.inline("« Bᴀᴄᴋ", data="mainmenu")],
]
@@ -62,8 +63,13 @@ _start = [
@callback("ownerinfo")
async def own(event):
+ msg = Owner_info_msg.format(
+ mention=event.sender.mention, me=inline_mention(ultroid_bot.me)
+ )
+ if custom_info:
+ msg += "\n\n• Powered by **@TheUltroid**"
await event.edit(
- Owner_info_msg,
+ msg,
buttons=[Button.inline("Close", data="closeit")],
link_preview=False,
)
@@ -76,45 +82,55 @@ async def closet(lol):
@asst_cmd(pattern="start ?(.*)", forwards=False, func=lambda x: not x.is_group)
async def ultroid(event):
- if not is_added(event.sender_id) and str(event.sender_id) not in owner_and_sudos():
+ args = event.pattern_match.group(1)
+ if not is_added(event.sender_id) and event.sender_id not in owner_and_sudos():
add_user(event.sender_id)
- kak_uiw = udB.get("OFF_START_LOG")
- if not kak_uiw or kak_uiw != "True":
+ kak_uiw = udB.get_key("OFF_START_LOG")
+ if not kak_uiw or kak_uiw != True:
msg = f"{inline_mention(event.sender)} `[{event.sender_id}]` started your [Assistant bot](@{asst.me.username})."
buttons = [[Button.inline("Info", "itkkstyo")]]
if event.sender.username:
- buttons[0].append(Button.url("User", "t.me/" + event.sender.username))
+ buttons[0].append(
+ Button.mention(
+ "User", await event.client.get_input_entity(event.sender_id)
+ )
+ )
await event.client.send_message(
- int(udB["LOG_CHANNEL"]), msg, buttons=buttons
+ udB.get_key("LOG_CHANNEL"), msg, buttons=buttons
)
- if (event.sender_id != OWNER_ID) and not is_fullsudo(event.sender_id):
+ if event.sender_id not in SUDO_M.fullsudos:
ok = ""
- u = await event.client.get_entity(event.chat_id)
- if not udB.get("STARTMSG"):
- if udB.get("PMBOT") == "True":
+ me = inline_mention(ultroid_bot.me)
+ mention = inline_mention(event.sender)
+ if args and args != "set":
+ await get_stored_file(event, args)
+ if not udB.get_key("STARTMSG"):
+ if udB.get_key("PMBOT"):
ok = "You can contact my master using this bot!!\n\nSend your Message, I will Deliver it To Master."
await event.reply(
- f"Hey there [{get_display_name(u)}](tg://user?id={u.id}), this is Ultroid Assistant of [{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.uid})!\n\n{ok}",
- file=udB.get("STARTMEDIA"),
+ f"Hey there {mention}, this is Ultroid Assistant of {me}!\n\n{ok}",
+ file=udB.get_key("STARTMEDIA"),
buttons=[Button.inline("Info.", data="ownerinfo")]
- if Owner_info_msg != "False"
+ if Owner_info_msg
else None,
)
else:
- me = f"[{ultroid_bot.me.first_name}](tg://user?id={ultroid_bot.uid})"
- mention = f"[{get_display_name(u)}](tg://user?id={u.id})"
await event.reply(
- udB.get("STARTMSG").format(me=me, mention=mention),
- file=udB.get("STARTMEDIA"),
- buttons=[Button.inline("Info.", data="ownerinfo")],
+ udB.get_key("STARTMSG").format(me=me, mention=mention),
+ file=udB.get_key("STARTMEDIA"),
+ buttons=[Button.inline("Info.", data="ownerinfo")]
+ if Owner_info_msg
+ else None,
)
else:
- name = get_display_name(event.sender_id)
- if event.pattern_match.group(1) == "set":
+ name = get_display_name(event.sender)
+ if args == "set":
await event.reply(
"Choose from the below options -",
buttons=_settings,
)
+ elif args:
+ await get_stored_file(event, args)
else:
await event.reply(
get_string("ast_3").format(name),
@@ -124,7 +140,7 @@ async def ultroid(event):
@callback("itkkstyo", owner=True)
async def ekekdhdb(e):
- text = f"When New Visitor will visit your Assistant Bot. You will get this log message!\n\nTo Disable : {HNDLR}setredis OFF_START_LOG True"
+ text = f"When New Visitor will visit your Assistant Bot. You will get this log message!\n\nTo Disable : {HNDLR}setdb OFF_START_LOG True"
await e.answer(text, alert=True)
@@ -138,7 +154,7 @@ async def ultroid(event):
@callback("stat", owner=True)
async def botstat(event):
- ok = len(get_all_users())
+ ok = len(get_all_users("BOT_USERS"))
msg = """Ultroid Assistant - Stats
Total Users - {}""".format(
ok,
@@ -148,7 +164,7 @@ Total Users - {}""".format(
@callback("bcast", owner=True)
async def bdcast(event):
- ok = get_all_users()
+ ok = get_all_users("BOT_USERS")
await event.edit(f"• Broadcast to {len(ok)} users.")
async with event.client.conversation(OWNER_ID) as conv:
await conv.send_message(
@@ -163,7 +179,7 @@ async def bdcast(event):
start = datetime.now()
for i in ok:
try:
- await asst.send_message(int(i), response.message)
+ await asst.send_message(int(i), response)
success += 1
except BaseException:
fail += 1
diff --git a/assistant/ytdl.py b/assistant/ytdl.py
index 6832d211aeeb6df29eb7f53b8be379b4ca97a0d4..95ddf2ff57940039e15e6afec193074230850d59 100644
--- a/assistant/ytdl.py
+++ b/assistant/ytdl.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2020 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -8,26 +8,30 @@
import os
import re
-import time
-from pyUltroid.functions.helper import (
- bash,
- download_file,
- fast_download,
- numerize,
- time_formatter,
- uploader,
-)
-from pyUltroid.functions.ytdl import dler, get_buttons, get_data
+try:
+ from PIL import Image
+except ImportError:
+ Image = None
+from pyUltroid.functions.helper import bash, fast_download, numerize, time_formatter
+from pyUltroid.functions.ytdl import dler, get_buttons, get_formats
from telethon import Button
+from telethon.errors.rpcerrorlist import FilePartLengthInvalidError, MediaEmptyError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from telethon.tl.types import InputWebDocument as wb
-from youtubesearchpython import VideosSearch
-from . import callback, in_pattern
+from . import LOGS, asst, callback, in_pattern, udB
+
+try:
+ from youtubesearchpython import VideosSearch
+except ImportError:
+ LOGS.info("'youtubesearchpython' not installed!")
+ VideosSearch = None
+
ytt = "https://telegra.ph/file/afd04510c13914a06dd03.jpg"
_yt_base_url = "https://www.youtube.com/watch?v="
+BACK_BUTTON = {}
@in_pattern("yt", owner=True)
@@ -67,13 +71,34 @@ async def _(event):
)
thumb = f"https://i.ytimg.com/vi/{ids}/hqdefault.jpg"
text = f"Title:- {title}\n"
- text += f"Duration:- {duration}
\n"
- text += f"Views:- {views}
\n"
- text += f"Publisher:- {publisher}
\n"
- text += f"Published:- {published_on}
\n"
- text += f"Description:- {description}
"
+ text += f"⏳ Duration:- {duration}
\n"
+ text += f"👀 Views:- {views}
\n"
+ text += f"🎙️ Publisher:- {publisher}
\n"
+ text += f"🗓️ Published on:- {published_on}
\n"
+ text += f"📝 Description:- {description}
"
desc = f"{title}\n{duration}"
file = wb(thumb, 0, "image/jpeg", [])
+ buttons = [
+ [
+ Button.inline("Audio", data=f"ytdl:audio:{ids}"),
+ Button.inline("Video", data=f"ytdl:video:{ids}"),
+ ],
+ [
+ Button.switch_inline(
+ "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
+ query="yt ",
+ same_peer=True,
+ ),
+ Button.switch_inline(
+ "Sʜᴀʀᴇ",
+ query=f"yt {string}",
+ same_peer=False,
+ ),
+ ],
+ ]
+ BACK_BUTTON.update(
+ {ids: {"text": text, "buttons": buttons, "parse_mode": "html"}}
+ )
results.append(
await event.builder.article(
type="photo",
@@ -84,24 +109,7 @@ async def _(event):
text=text,
include_media=True,
parse_mode="html",
- buttons=[
- [
- Button.inline("Audio", data=f"ytdl_audio_{ids}"),
- Button.inline("Video", data=f"ytdl_video_{ids}"),
- ],
- [
- Button.switch_inline(
- "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
- query="yt ",
- same_peer=True,
- ),
- Button.switch_inline(
- "Sʜᴀʀᴇ",
- query=f"yt {string}",
- same_peer=False,
- ),
- ],
- ],
+ buttons=buttons,
),
)
await event.answer(results[:50])
@@ -109,18 +117,16 @@ async def _(event):
@callback(
re.compile(
- "ytdl_(.*)",
+ "ytdl:(.*)",
),
owner=True,
)
async def _(e):
_e = e.pattern_match.group(1).decode("UTF-8")
- _lets_split = _e.split("_", maxsplit=1)
+ _lets_split = _e.split(":")
_ytdl_data = await dler(e, _yt_base_url + _lets_split[1])
- _data = get_data(_lets_split[0], _ytdl_data)
- _buttons = get_buttons(
- "ytdownload_" + _lets_split[0] + "_" + _lets_split[1] + ":", _data
- )
+ _data = get_formats(_lets_split[0], _lets_split[1], _ytdl_data)
+ _buttons = get_buttons(_data)
_text = "`Select Your Format.`"
if not _buttons:
_text = "`Error downloading from YouTube.\nTry Restarting your bot.`"
@@ -129,26 +135,36 @@ async def _(e):
@callback(
re.compile(
- "ytdownload_(.*)",
+ "ytdownload:(.*)",
),
owner=True,
)
async def _(event):
url = event.pattern_match.group(1).decode("UTF-8")
- lets_split = url.split("_", maxsplit=1)
- vid_id = lets_split[1].split(":")[0]
+ lets_split = url.split(":")
+ vid_id = lets_split[2]
link = _yt_base_url + vid_id
- format = url.split(":")[1]
+ format = lets_split[1]
+ try:
+ ext = lets_split[3]
+ except IndexError:
+ ext = "mp3"
if lets_split[0] == "audio":
opts = {
- "format": str(format),
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
- "outtmpl": "%(id)s.mp3",
- "quiet": True,
+ "outtmpl": "%(id)s." + ext,
"logtostderr": False,
+ "postprocessors": [
+ {
+ "key": "FFmpegExtractAudio",
+ "preferredcodec": ext,
+ "preferredquality": format,
+ },
+ {"key": "FFmpegMetadata"},
+ ],
}
ytdl_data = await dler(event, link, opts, True)
title = ytdl_data["title"]
@@ -158,16 +174,22 @@ async def _(event):
artist = ytdl_data["creator"]
elif ytdl_data.get("channel"):
artist = ytdl_data["channel"]
- views = numerize(ytdl_data["view_count"])
- await download_file(
- f"https://i.ytimg.com/vi/{vid_id}/hqdefault.jpg", f"{title}.jpg"
+ views = numerize(ytdl_data.get("view_count")) or 0
+ thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=vid_id + ".jpg")
+ likes = numerize(ytdl_data.get("like_count")) or 0
+ duration = ytdl_data.get("duration") or 0
+ description = (
+ ytdl_data["description"]
+ if len(ytdl_data["description"]) < 100
+ else ytdl_data["description"][:100]
)
- thumb = f"{title}.jpg"
- duration = ytdl_data["duration"]
- os.rename(f"{ytdl_data['id']}.mp3", f"{title}.mp3")
- c_time = time.time()
- file = await uploader(
- f"{title}.mp3", f"{title}.mp3", c_time, event, "Uploading " + title + "..."
+ description = description or "None"
+ file, _ = await event.client.fast_uploader(
+ vid_id + f".{ext}" * 2,
+ filename=title + "." + ext,
+ show_progress=True,
+ event=event,
+ to_delete=True,
)
attributes = [
DocumentAttributeAudio(
@@ -183,9 +205,9 @@ async def _(event):
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
- "outtmpl": "%(id)s.mp4",
+ "outtmpl": "%(id)s." + ext,
"logtostderr": False,
- "quiet": True,
+ "postprocessors": [{"key": "FFmpegMetadata"}],
}
ytdl_data = await dler(event, link, opts, True)
title = ytdl_data["title"]
@@ -195,24 +217,30 @@ async def _(event):
artist = ytdl_data["creator"]
elif ytdl_data.get("channel"):
artist = ytdl_data["channel"]
- views = numerize(ytdl_data["view_count"])
- thumb = await fast_download(
- f"https://i.ytimg.com/vi/{vid_id}/hqdefault.jpg", filename=f"{title}.jpg"
- )
- hi, wi = ytdl_data["height"], ytdl_data["width"]
- duration = ytdl_data["duration"]
+ views = numerize(ytdl_data.get("view_count")) or 0
+ thumb, _ = await fast_download(ytdl_data["thumbnail"], filename=vid_id + ".jpg")
try:
- os.rename(f"{ytdl_data['id']}.mp4", f"{title}.mp4")
- except FileNotFoundError:
- try:
- os.rename(f"{ytdl_data['id']}.mkv", f"{title}.mp4")
- except FileNotFoundError:
- os.rename(f"{ytdl_data['id']}.mp4.webm", f"{title}.mp4")
- except Exception as ex:
- return await event.edit(str(ex))
- c_time = time.time()
- file = await uploader(
- f"{title}.mp4", f"{title}.mp4", c_time, event, "Uploading " + title + "..."
+ Image.open(thumb).save(thumb, "JPEG")
+ except Exception as er:
+ LOGS.exception(er)
+ thumb = None
+ description = (
+ ytdl_data["description"]
+ if len(ytdl_data["description"]) < 100
+ else ytdl_data["description"][:100]
+ )
+ likes = numerize(ytdl_data.get("like_count")) or 0
+ hi, wi = ytdl_data.get("height") or 720, ytdl_data.get("width") or 1280
+ duration = ytdl_data.get("duration") or 0
+ filepath = vid_id + ".mkv"
+ if not os.path.exists(filepath):
+ filepath = filepath + ".webm"
+ file, _ = await event.client.fast_uploader(
+ filepath,
+ filename=title + ".mkv",
+ show_progress=True,
+ event=event,
+ to_delete=True,
)
attributes = [
DocumentAttributeVideo(
@@ -222,15 +250,37 @@ async def _(event):
supports_streaming=True,
),
]
- text = f"**Title:** `{title}`\n"
- text += f"**Duration:** `{time_formatter(int(duration)*1000)}`\n"
- text += f"**Views:** `{views}`\n"
- text += f"**Artist:** `{artist}`\n\n"
- await event.edit(
- text,
- file=file,
- buttons=Button.switch_inline("Search More", query="yt ", same_peer=True),
- attributes=attributes,
- thumb=thumb,
- )
- await bash(f'rm "{title}"*')
+ text = f"**Title:** `{title}`\n\n"
+ text += f"`📝 Description:` `{description}`\n\n"
+ text += f"`⏳ Duration:` `{time_formatter(int(duration)*1000)}`\n"
+ text += f"`🎤 Artist:` `{artist}`\n"
+ text += f"`👀 Views`: `{views}`\n"
+ text += f"`👍 Likes`: `{likes}`\n"
+ button = Button.switch_inline("Search More", query="yt ", same_peer=True)
+ try:
+ await event.edit(
+ text,
+ file=file,
+ buttons=button,
+ attributes=attributes,
+ thumb=thumb,
+ )
+ except (FilePartLengthInvalidError, MediaEmptyError):
+ file = await asst.send_message(
+ udB.get_key("LOG_CHANNEL"),
+ text,
+ file=file,
+ buttons=button,
+ attributes=attributes,
+ thumb=thumb,
+ )
+ await event.edit(text, file=file.media, buttons=button)
+ await bash(f"rm {vid_id}.jpg")
+
+
+@callback(re.compile("ytdl_back:(.*)"), owner=True)
+async def ytdl_back(event):
+ id_ = event.data_match.group(1).decode("utf-8")
+ if not BACK_BUTTON.get(id_):
+ return await event.answer("Query Expired! Search again 🔍")
+ await event.edit(**BACK_BUTTON[id_])
diff --git a/plugins/__init__.py b/plugins/__init__.py
index 86aca2af5d53a6abfb239460587d36d95d972d82..f4a10101f18f9e13743a2f53f9835bd3a0fba812 100644
--- a/plugins/__init__.py
+++ b/plugins/__init__.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -11,7 +11,7 @@ import time
from random import choice
from pyUltroid import *
-from pyUltroid.dB import ULTROID_IMAGES
+from pyUltroid.dB import DEVLIST, ULTROID_IMAGES
from pyUltroid.functions.helper import *
from pyUltroid.functions.info import *
from pyUltroid.functions.misc import *
@@ -25,15 +25,20 @@ from telethon.tl import functions, types
from strings import get_string
-Redis = udB.get
-client = bot = ultroid_bot
+Redis = udB.get_key
-OWNER_NAME = ultroid_bot.me.first_name
-OWNER_ID = ultroid_bot.me.id
-LOG_CHANNEL = int(udB.get("LOG_CHANNEL"))
-INLINE_PIC = udB.get("INLINE_PIC") or choice(ULTROID_IMAGES)
-if INLINE_PIC == "False":
+OWNER_NAME = ultroid_bot.full_name
+OWNER_ID = ultroid_bot.uid
+
+LOG_CHANNEL = udB.get_key("LOG_CHANNEL")
+
+INLINE_PIC = udB.get_key("INLINE_PIC")
+
+if INLINE_PIC is None:
+ INLINE_PIC = choice(ULTROID_IMAGES)
+elif INLINE_PIC == False:
INLINE_PIC = None
+
Telegraph = telegraph_client()
List = []
diff --git a/plugins/_chatactions.py b/plugins/_chatactions.py
index 15e4fe27752953193bb4deac52b9ce6074b51dc5..2cc519255abc39d579fd749bf3e07d5004102081 100644
--- a/plugins/_chatactions.py
+++ b/plugins/_chatactions.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -8,12 +8,10 @@
import asyncio
from pyUltroid.dB import stickers
-from pyUltroid.dB.chatBot_db import chatbot_stats
-from pyUltroid.dB.clean_db import is_clean_added
from pyUltroid.dB.forcesub_db import get_forcesetting
from pyUltroid.dB.gban_mute_db import is_gbanned
from pyUltroid.dB.greetings_db import get_goodbye, get_welcome, must_thank
-from pyUltroid.dB.username_db import get_username, update_username
+from pyUltroid.dB.nsfw_db import is_profan
from pyUltroid.functions.helper import inline_mention
from pyUltroid.functions.tools import create_tl_btn, get_chatbot_reply
from telethon import events
@@ -21,6 +19,10 @@ from telethon.errors.rpcerrorlist import UserNotParticipantError
from telethon.tl.functions.channels import GetParticipantRequest
from telethon.utils import get_display_name
+try:
+ from ProfanityDetector import detector
+except ImportError:
+ detector = None
from . import LOG_CHANNEL, LOGS, asst, get_string, types, udB, ultroid_bot
from ._inline import something
@@ -28,7 +30,8 @@ from ._inline import something
@ultroid_bot.on(events.ChatAction())
async def ChatActionsHandler(ult): # sourcery no-metrics
# clean chat actions
- if is_clean_added(ult.chat_id):
+ key = udB.get_key("CLEANCHAT") or []
+ if ult.chat_id in key:
try:
await ult.delete()
except BaseException:
@@ -43,7 +46,7 @@ async def ChatActionsHandler(ult): # sourcery no-metrics
await ult.respond(file=sticker)
# force subscribe
if (
- udB.get("FORCESUB")
+ udB.get_key("FORCESUB")
and ((ult.user_joined or ult.user_added))
and get_forcesetting(ult.chat_id)
):
@@ -83,7 +86,10 @@ async def ChatActionsHandler(ult): # sourcery no-metrics
user = await ult.get_user()
chat = await ult.get_chat()
title = chat.title or "this chat"
- count = (await ult.client.get_participants(chat, limit=0)).total
+ count = (
+ chat.participants_count
+ or (await ult.client.get_participants(chat, limit=0)).total
+ )
mention = inline_mention(user)
name = user.first_name
fullname = get_display_name(user)
@@ -120,7 +126,10 @@ async def ChatActionsHandler(ult): # sourcery no-metrics
user = await ult.get_user()
chat = await ult.get_chat()
title = chat.title or "this chat"
- count = (await ult.client.get_participants(chat, limit=0)).total
+ count = (
+ chat.participants_count
+ or (await ult.client.get_participants(chat, limit=0)).total
+ )
mention = inline_mention(user)
name = user.first_name
fullname = get_display_name(user)
@@ -160,9 +169,12 @@ async def chatBot_replies(e):
sender = await e.get_sender()
if not isinstance(sender, types.User):
return
- if e.text and chatbot_stats(e.chat_id, e.sender_id):
+ key = udB.get_key("CHATBOT_USERS") or {}
+ if e.text and key.get(e.chat_id) and sender.id in key[e.chat_id]:
msg = await get_chatbot_reply(e.message.message)
if msg:
+ sleep = udB.get_key("CHATBOT_SLEEP") or 1.5
+ await asyncio.sleep(sleep)
await e.reply(msg)
chat = await e.get_chat()
if e.is_group and not sender.bot:
@@ -171,6 +183,10 @@ async def chatBot_replies(e):
elif e.is_private and not sender.bot:
if chat.username:
await uname_stuff(e.sender_id, chat.username, chat.first_name)
+ if detector and is_profan(e.chat_id) and e.text:
+ x, y = detector(e.text)
+ if y:
+ await e.delete()
@ultroid_bot.on(events.Raw(types.UpdateUserName))
@@ -179,8 +195,9 @@ async def uname_change(e):
async def uname_stuff(id, uname, name):
- if udB.get("USERNAME_LOG") == "True":
- old = get_username(id)
+ if udB.get_key("USERNAME_LOG") == "True":
+ old_ = udB.get_key("USERNAME_DB") or {}
+ old = old_.get(id)
# Ignore Name Logs
if old and old == uname:
return
@@ -199,4 +216,6 @@ async def uname_stuff(id, uname, name):
LOG_CHANNEL,
get_string("can_4").format(f"[{name}](tg://user?id={id})", uname),
)
- update_username(id, uname)
+
+ old_[id] = uname
+ udB.set_key("USERNAME_DB", str(old_))
diff --git a/plugins/_help.py b/plugins/_help.py
index 4477cd778f76a4a5e18dffc62c4d7a64f314fa2a..5a92e3a256047742c09ab8e0b5d2acadbbff5ec9 100644
--- a/plugins/_help.py
+++ b/plugins/_help.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -14,15 +14,15 @@ from telethon.errors.rpcerrorlist import (
)
from telethon.tl.custom import Button
-from . import *
+from . import HNDLR, INLINE_PIC, LOGS, OWNER_NAME, asst, get_string, udB, ultroid_cmd
_main_help_menu = [
[
- Button.inline(get_string("help_4"), data="hrrrr"),
- Button.inline(get_string("help_5"), data="frrr"),
+ Button.inline(get_string("help_4"), data="uh_Official_"),
+ Button.inline(get_string("help_5"), data="uh_Addons_"),
],
[
- Button.inline(get_string("help_6"), data="vc_helper"),
+ Button.inline(get_string("help_6"), data="uh_VCBot_"),
Button.inline(get_string("help_7"), data="inlone"),
],
[
@@ -38,6 +38,7 @@ _main_help_menu = [
@ultroid_cmd(pattern="help ?(.*)")
async def _help(ult):
plug = ult.pattern_match.group(1)
+ chat = await ult.get_chat()
if plug:
try:
if plug in HELP["Official"]:
@@ -45,19 +46,19 @@ async def _help(ult):
for i in HELP["Official"][plug]:
output += i
output += "\n© @TeamUltroid"
- await eor(ult, output)
+ await ult.eor(output)
elif HELP.get("Addons") and plug in HELP["Addons"]:
output = f"**Plugin** - `{plug}`\n"
for i in HELP["Addons"][plug]:
output += i
output += "\n© @TeamUltroid"
- await eor(ult, output)
+ await ult.eor(output)
elif HELP.get("VCBot") and plug in HELP["VCBot"]:
output = f"**Plugin** - `{plug}`\n"
for i in HELP["VCBot"][plug]:
output += i
output += "\n© @TeamUltroid"
- await eor(ult, output)
+ await ult.eor(output)
else:
try:
x = get_string("help_11").format(plug)
@@ -65,12 +66,12 @@ async def _help(ult):
x += HNDLR + d
x += "\n"
x += "\n© @TeamUltroid"
- await eor(ult, x)
+ await ult.eor(x)
except BaseException:
- await eor(ult, get_string("help_1").format(plug), time=5)
+ await ult.eor(get_string("help_1").format(plug), time=5)
except BaseException as er:
LOGS.exception(er)
- await eor(ult, "Error 🤔 occured.")
+ await ult.eor("Error 🤔 occured.")
else:
try:
results = await ult.client.inline_query(asst.me.username, "ultd")
@@ -80,12 +81,12 @@ async def _help(ult):
for y in x:
z.append(y)
cmd = len(z) + 10
- if udB.get("MANAGER") and udB.get("DUAL_HNDLR") == "/":
+ if udB.get_key("MANAGER") and udB.get_key("DUAL_HNDLR") == "/":
_main_help_menu[2:3] = [[Button.inline("• Manager Help •", "mngbtn")]]
return await ult.reply(
get_string("inline_4").format(
OWNER_NAME,
- len(HELP["Official"]) - 5,
+ len(HELP["Official"]),
len(HELP["Addons"] if "Addons" in HELP else []),
cmd,
),
@@ -93,11 +94,10 @@ async def _help(ult):
buttons=_main_help_menu,
)
except BotResponseTimeoutError:
- return await eor(
- ult,
+ return await ult.eor(
get_string("help_2").format(HNDLR),
)
except BotInlineDisabledError:
- return await eor(ult, get_string("help_3"))
- await results[0].click(ult.chat_id, reply_to=ult.reply_to_msg_id, hide_via=True)
+ return await ult.eor(get_string("help_3"))
+ await results[0].click(chat.id, reply_to=ult.reply_to_msg_id, hide_via=True)
await ult.delete()
diff --git a/plugins/_inline.py b/plugins/_inline.py
index b40a5ca565a701c20db4747fbb75e17bd8f59bcb..c52332694397e86e182801ad6e55539fb23722fe 100644
--- a/plugins/_inline.py
+++ b/plugins/_inline.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -8,13 +8,12 @@
import re
import time
from datetime import datetime
-from math import ceil
from os import remove
from git import Repo
from pyUltroid.dB._core import HELP, LIST
from pyUltroid.functions.helper import gen_chlog, time_formatter, updater
-from pyUltroid.misc import CMD_HELP, owner_and_sudos
+from pyUltroid.functions.misc import split_list
from pyUltroid.misc._assistant import callback, in_pattern
from telethon import Button
from telethon.tl.types import InputWebDocument, Message
@@ -24,18 +23,19 @@ from . import HNDLR, INLINE_PIC, LOGS, OWNER_NAME, asst, get_string, start_time,
from ._help import _main_help_menu
# ================================================#
-notmine = f"This bot is for {OWNER_NAME}"
-TLINK = INLINE_PIC or "https://telegra.ph/file/d9c9bc13647fa1d96e764.jpg"
+TLINK = INLINE_PIC or "https://telegra.ph/file/74d6259983e0642923fdb.jpg"
helps = get_string("inline_1")
-add_ons = udB.get("ADDONS")
-if add_ons == "True" or add_ons is None:
+add_ons = udB.get_key("ADDONS")
+
+if add_ons is not False:
zhelps = get_string("inline_2")
else:
zhelps = get_string("inline_3")
-
+PLUGINS = HELP.get("Official", [])
+ADDONS = HELP.get("Addons", [])
upage = 0
# ============================================#
@@ -55,7 +55,7 @@ SUP_BUTTONS = [
async def inline_alive(o):
MSG = "• **Ultroid Userbot •**"
WEB0 = InputWebDocument(
- "https://telegra.ph/file/55dd0f381c70e72557cb1.jpg", 0, "image/jpg", []
+ "https://telegra.ph/file/acd4f5d61369f74c5e7a7.jpg", 0, "image/jpg", []
)
RES = [
await o.builder.article(
@@ -76,15 +76,12 @@ async def inline_alive(o):
@in_pattern("ultd", owner=True)
async def inline_handler(event):
z = []
- PLUGINS = HELP["Official"] if "Official" in HELP.keys() else []
- ADDONS = HELP["Addons"] if "Addons" in HELP.keys() else []
for x in LIST.values():
- for y in x:
- z.append(y)
+ z.extend(x)
text = get_string("inline_4").format(
OWNER_NAME,
- len(PLUGINS),
- len(ADDONS),
+ len(HELP.get("Official", [])),
+ len(HELP.get("Addons", [])),
len(z),
)
if INLINE_PIC:
@@ -122,16 +119,13 @@ async def _(event):
@callback("ownr", owner=True)
async def setting(event):
z = []
- PLUGINS = HELP["Official"] if "Official" in HELP.keys() else []
- ADDONS = HELP["Addons"] if "Addons" in HELP.keys() else []
for x in LIST.values():
- for y in x:
- z.append(y)
+ z.extend(x)
await event.edit(
get_string("inline_4").format(
OWNER_NAME,
- len(PLUGINS),
- len(ADDONS),
+ len(HELP.get("Official", [])),
+ len(HELP.get("Addons", [])),
len(z),
),
file=INLINE_PIC,
@@ -150,14 +144,73 @@ async def setting(event):
)
-@callback(data="vc_helper", owner=True)
-async def on_vc_callback_query_handler(event):
- xhelps = get_string("inline_6").format(OWNER_NAME, len(HELP["VCBot"]))
+_strings = {"Official": helps, "Addons": zhelps, "VCBot": get_string("inline_6")}
+
+
+@callback(re.compile("uh_(.*)"), owner=True)
+async def help_func(ult):
+ key, count = ult.data_match.group(1).decode("utf-8").split("_")
+ if key == "VCBot" and HELP.get("VCBot") is None:
+ return await ult.answer(get_string("help_12"), alert=True)
+ elif key == "Addons" and HELP.get("Addons") is None:
+ return await ult.answer(get_string("help_13").format(HNDLR), alert=True)
+ if "|" in count:
+ _, count = count.split("|")
+ count = 0 if not count else int(count)
+ text = _strings.get(key, "").format(OWNER_NAME, len(HELP.get(key)))
+ await ult.edit(
+ text, file=INLINE_PIC, buttons=page_num(count, key), link_preview=False
+ )
+
+
+@callback(re.compile("uplugin_(.*)"), owner=True)
+async def uptd_plugin(event):
+ key, file = event.data_match.group(1).decode("utf-8").split("_")
+ index = None
+ if "|" in file:
+ file, index = file.split("|")
+ key_ = HELP.get(key, [])
+ hel_p = f"Plugin Name - `{file}`\n"
+ help_ = ""
+ try:
+ for i in key_[file]:
+ help_ += i
+ except BaseException:
+ if file in LIST:
+ help_ = get_string("help_11").format(file)
+ for d in LIST[file]:
+ help_ += HNDLR + d
+ help_ += "\n"
+ if not help_:
+ help_ = f"{file} has no Detailed Help!"
+ help_ += "\n© Join @TeamUltroid"
+ buttons = []
+ if INLINE_PIC:
+ data = f"sndplug_{key}_{file}"
+ if index is not None:
+ data += f"|{index}"
+ buttons.append(
+ [
+ Button.inline(
+ "« Sᴇɴᴅ Pʟᴜɢɪɴ »",
+ data=data,
+ )
+ ]
+ )
+ data = f"uh_{key}_"
+ if index is not None:
+ data += f"|{index}"
+ buttons.append(
+ [
+ Button.inline("« Bᴀᴄᴋ", data=data),
+ ]
+ )
try:
- buttons = page_num(0, HELP["VCBot"].keys(), "vchelp", "vc")
- except (ZeroDivisionError, KeyError):
- return await event.answer("Vc not Active.")
- await event.edit(xhelps, file=INLINE_PIC, buttons=buttons, link_preview=False)
+ await event.edit(help_, buttons=buttons)
+ except Exception as er:
+ LOGS.exception(er)
+ help = f"Do `{HNDLR}help {key}` to get list of commands."
+ await event.edit(help, buttons=buttons)
@callback(data="doupdate", owner=True)
@@ -165,10 +218,11 @@ async def _(event):
if not updater():
return await event.answer(get_string("inline_9"), cache_time=0, alert=True)
if not INLINE_PIC:
- return await event.answer(f"Do {HNDLR}update")
+ return await event.answer(f"Do '{HNDLR}update' to update..")
repo = Repo.init()
- ac_br = repo.active_branch
- changelog, tl_chnglog = gen_chlog(repo, f"HEAD..upstream/{ac_br}")
+ changelog, tl_chnglog = await gen_chlog(
+ repo, f"HEAD..upstream/{repo.active_branch}"
+ )
changelog_str = changelog + "\n\n" + get_string("inline_8")
if len(changelog_str) > 1024:
await event.edit(get_string("upd_4"))
@@ -261,6 +315,19 @@ async def _(e):
same_peer=True,
),
],
+ [
+ Button.switch_inline(
+ "Tᴡɪᴛᴛᴇʀ Usᴇʀ", query="twitter theultroid", same_peer=True
+ ),
+ Button.switch_inline(
+ "Kᴏᴏ Sᴇᴀʀᴄʜ", query="koo @__kumar__amit", same_peer=True
+ ),
+ ],
+ [
+ Button.switch_inline(
+ "Fᴅʀᴏɪᴅ Sᴇᴀʀᴄʜ", query="fdroid telegram", same_peer=True
+ )
+ ],
[
Button.inline(
"« Bᴀᴄᴋ",
@@ -271,124 +338,16 @@ async def _(e):
await e.edit(buttons=button, link_preview=False)
-@callback(data="hrrrr", owner=True)
-async def on_plug_in_callback_query_handler(event):
- xhelps = helps.format(OWNER_NAME, len(HELP["Official"]))
- buttons = page_num(0, HELP["Official"].keys(), "helpme", "def")
- await event.edit(f"{xhelps}", buttons=buttons, link_preview=False)
-
-
-@callback(data="frrr", owner=True)
-async def addon(event):
- if HELP.get("Addons"):
- halp = zhelps.format(OWNER_NAME, len(HELP["Addons"]))
- buttons = page_num(0, HELP["Addons"].keys(), "addon", "add")
- await event.edit(halp, buttons=buttons, link_preview=False)
- else:
- await event.answer(
- f"• Tʏᴘᴇ {HNDLR}setredis ADDONS True\n Tᴏ ɢᴇᴛ ᴀᴅᴅᴏɴs ᴘʟᴜɢɪɴs",
- cache_time=0,
- alert=True,
- )
-
-
-@callback(
- data=re.compile(
- rb"helpme_next\((.+?)\)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- current_page_number = int(event.data_match.group(1).decode("UTF-8"))
- buttons = page_num(
- current_page_number + 1, HELP["Official"].keys(), "helpme", "def"
- )
- await event.edit(buttons=buttons, link_preview=False)
-
-
-@callback(
- data=re.compile(
- rb"helpme_prev\((.+?)\)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- current_page_number = int(event.data_match.group(1).decode("UTF-8"))
- buttons = page_num(
- current_page_number - 1, list(HELP["Official"].keys()), "helpme", "def"
- )
- await event.edit(buttons=buttons, link_preview=False)
-
-
-@callback(
- data=re.compile(
- rb"addon_next\((.+?)\)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- current_page_number = int(event.data_match.group(1).decode("UTF-8"))
- buttons = page_num(
- current_page_number + 1, list(HELP["Addons"].keys()), "addon", "add"
- )
- await event.edit(buttons=buttons, link_preview=False)
-
-
-@callback(
- data=re.compile(
- rb"addon_prev\((.+?)\)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- current_page_number = int(event.data_match.group(1).decode("UTF-8"))
- buttons = page_num(
- current_page_number - 1, list(HELP["Addons"].keys()), "addon", "add"
- )
- await event.edit(buttons=buttons, link_preview=False)
-
-
-@callback(data="back", owner=True)
-async def backr(event):
- xhelps = helps.format(OWNER_NAME, len(HELP["Official"]))
- current_page_number = int(upage)
- buttons = page_num(
- current_page_number, list(HELP["Official"].keys()), "helpme", "def"
- )
- await event.edit(
- xhelps,
- file=INLINE_PIC,
- buttons=buttons,
- link_preview=False,
- )
-
-
-@callback(data="buck", owner=True)
-async def backr(event):
- xhelps = zhelps.format(OWNER_NAME, len(HELP["Addons"]))
- current_page_number = int(upage)
- buttons = page_num(current_page_number, list(HELP["Addons"].keys()), "addon", "add")
- await event.edit(
- xhelps,
- file=INLINE_PIC,
- buttons=buttons,
- link_preview=False,
- )
-
-
@callback(data="open", owner=True)
async def opner(event):
z = []
- PLUGINS = HELP["Official"] if "Official" in HELP.keys() else []
- ADDONS = HELP["Addons"] if "Addons" in HELP.keys() else []
for x in LIST.values():
- for y in x:
- z.append(y)
+ z.extend(x)
await event.edit(
get_string("inline_4").format(
OWNER_NAME,
- len(PLUGINS),
- len(ADDONS),
+ len(HELP.get("Official", [])),
+ len(HELP.get("Addons", [])),
len(z),
),
buttons=_main_help_menu,
@@ -404,211 +363,44 @@ async def on_plug_in_callback_query_handler(event):
)
-@callback(
- data=re.compile(
- b"def_plugin_(.*)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- plugin_name = event.data_match.group(1).decode("UTF-8")
- help_string = f"Plugin Name - `{plugin_name}`\n"
- try:
- for i in HELP["Official"][plugin_name]:
- help_string += i
- except BaseException:
- pass
- if help_string == "":
- reply_pop_up_alert = f"{plugin_name} has no detailed help..."
- else:
- reply_pop_up_alert = help_string
- reply_pop_up_alert += "\n© @TeamUltroid"
- buttons = []
- if INLINE_PIC:
- buttons.append(
- [
- Button.inline(
- "« Sᴇɴᴅ Pʟᴜɢɪɴ »",
- data=f"sndplug_{(event.data).decode('UTF-8')}",
- )
- ]
- )
- buttons.append(
- [
- Button.inline("« Bᴀᴄᴋ", data="back"),
- ]
- )
- try:
- if str(event.query.user_id) in owner_and_sudos():
- await event.edit(
- reply_pop_up_alert,
- buttons=buttons,
- )
- else:
- reply_pop_up_alert = notmine
- await event.answer(reply_pop_up_alert, cache_time=0)
- except BaseException:
- await event.edit(get_string("inline_7").format(plugin_name), buttons=buttons)
-
-
-@callback(
- data=re.compile(
- b"vc_plugin_(.*)",
- ),
- owner=True,
-)
-async def on_vc_plg_callback_query_handler(event):
- plugin_name = event.data_match.group(1).decode("UTF-8")
- help_string = f"Plugin Name - `{plugin_name}`\n"
- try:
- for i in HELP["VCBot"][plugin_name]:
- help_string += i
- except BaseException:
- pass
- if help_string == "**Commands Available:**\n\n":
- reply_pop_up_alert = f"{plugin_name} has no detailed help..."
- else:
- reply_pop_up_alert = help_string
- reply_pop_up_alert += "\n© @TeamUltroid"
- buttons = []
- if INLINE_PIC:
- buttons.append(
- [
- Button.inline(
- "« Sᴇɴᴅ Pʟᴜɢɪɴ »",
- data=f"sndplug_{(event.data).decode('UTF-8')}",
- )
- ]
- )
- buttons.append(
- [
- Button.inline("« Bᴀᴄᴋ", data="vc_helper"),
- ]
- )
- try:
- if str(event.query.user_id) in owner_and_sudos():
- await event.edit(
- reply_pop_up_alert,
- buttons=buttons,
- )
- else:
- reply_pop_up_alert = notmine
- await event.answer(reply_pop_up_alert, cache_time=0)
- except BaseException:
- halps = f"Do .help {plugin_name} to get the list of commands."
- await event.edit(halps, buttons=buttons)
-
-
-@callback(
- data=re.compile(
- b"add_plugin_(.*)",
- ),
- owner=True,
-)
-async def on_plug_in_callback_query_handler(event):
- plugin_name = event.data_match.group(1).decode("UTF-8")
- help_string = ""
+def page_num(index, key):
+ rows = udB.get_key("HELP_ROWS") or 5
+ cols = udB.get_key("HELP_COLUMNS") or 2
+ loaded = HELP.get(key, [])
+ emoji = udB.get_key("EMOJI_IN_HELP") or "✘"
+ List = [
+ Button.inline(f"{emoji} {x} {emoji}", data=f"uplugin_{key}_{x}|{index}")
+ for x in sorted(loaded)
+ ]
+ all_ = split_list(List, cols)
+ fl_ = split_list(all_, rows)
try:
- for i in HELP["Addons"][plugin_name]:
- help_string += i
- except BaseException:
- try:
- for u in CMD_HELP[plugin_name]:
- help_string = get_string("help_11").format(plugin_name)
- help_string += str(CMD_HELP[plugin_name])
- except BaseException:
- try:
- if plugin_name in LIST:
- help_string = get_string("help_11").format(plugin_name)
- for d in LIST[plugin_name]:
- help_string += HNDLR + d
- help_string += "\n"
- except BaseException:
- pass
- if help_string == "":
- reply_pop_up_alert = f"{plugin_name} has no detailed help..."
+ new_ = fl_[index]
+ except IndexError:
+ new_ = fl_[0] if fl_ else []
+ index = 0
+ if index == 0 and len(fl_) == 1:
+ new_.append([Button.inline("« Bᴀᴄᴋ »", data="open")])
else:
- reply_pop_up_alert = help_string
- reply_pop_up_alert += "\n© @TeamUltroid"
- buttons = []
- if INLINE_PIC:
- buttons.append(
+ new_.append(
[
- Button.inline(
- "« Sᴇɴᴅ Pʟᴜɢɪɴ »",
- data=f"sndplug_{(event.data).decode('UTF-8')}",
- )
- ]
- )
- buttons.append(
- [
- Button.inline("« Bᴀᴄᴋ", data="buck"),
- ]
- )
- try:
- if str(event.query.user_id) in owner_and_sudos():
- await event.edit(
- reply_pop_up_alert,
- buttons=buttons,
- )
- else:
- reply_pop_up_alert = notmine
- await event.answer(reply_pop_up_alert, cache_time=0)
- except BaseException:
- halps = get_string("inline_7").format(plugin_name)
- await event.edit(halps, buttons=buttons)
-
-
-def page_num(page_number, loaded_plugins, prefix, type_):
- number_of_rows = 5
- number_of_cols = 2
- emoji = udB.get("EMOJI_IN_HELP")
- multi = emoji or "✘"
- global upage
- upage = page_number
- helpable_plugins = [p for p in loaded_plugins]
- helpable_plugins = sorted(helpable_plugins)
- modules = [
- Button.inline(
- "{} {} {}".format(
- multi,
- x,
- multi,
- ),
- data=f"{type_}_plugin_{x}",
- )
- for x in helpable_plugins
- ]
- pairs = list(zip(modules[::number_of_cols], modules[1::number_of_cols]))
- if len(modules) % number_of_cols == 1:
- pairs.append((modules[-1],))
- max_num_pages = ceil(len(pairs) / number_of_rows)
- modulo_page = page_number % max_num_pages
- if len(pairs) > number_of_rows:
- pairs = pairs[
- modulo_page * number_of_rows : number_of_rows * (modulo_page + 1)
- ] + [
- (
Button.inline(
"« Pʀᴇᴠɪᴏᴜs",
- data=f"{prefix}_prev({modulo_page})",
+ data=f"uh_{key}_{index-1}",
),
Button.inline("« Bᴀᴄᴋ »", data="open"),
Button.inline(
"Nᴇxᴛ »",
- data=f"{prefix}_next({modulo_page})",
+ data=f"uh_{key}_{index+1}",
),
- ),
- ]
- else:
- pairs = pairs[
- modulo_page * number_of_rows : number_of_rows * (modulo_page + 1)
- ] + [(Button.inline("« Bᴀᴄᴋ »", data="open"),)]
- return pairs
+ ]
+ )
+ return new_
# --------------------------------------------------------------------------------- #
+
STUFF = {}
@@ -619,9 +411,9 @@ async def ibuild(e):
if not (n and n.isdigit()):
return
ok = STUFF.get(int(n))
- txt = ok.get("msg") or None
- pic = ok.get("media") or None
- btn = ok.get("button") or None
+ txt = ok.get("msg")
+ pic = ok.get("media")
+ btn = ok.get("button")
if not (pic or txt):
txt = "Hey!"
if pic:
@@ -701,4 +493,4 @@ async def something(e, msg, media, button, reply=True, chat=None):
)
except Exception as er:
- LOGS.info(er)
+ LOGS.exception(er)
diff --git a/plugins/_ultroid.py b/plugins/_ultroid.py
index 2a1a19f801804851ec5b53ba97cc128c96116dd1..71cf2c9ecfc5da10536ad19c085e9126eb5cc27c 100644
--- a/plugins/_ultroid.py
+++ b/plugins/_ultroid.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -35,7 +35,7 @@ ULTSTRING = """🎇 **Thanks for Deploying Ultroid Userbot!**
@ultroid_cmd(
pattern="repo$",
- type=["official", "manager"],
+ manager=True,
)
async def repify(e):
try:
@@ -50,7 +50,7 @@ async def repify(e):
pass
except Exception as er:
LOGS.info("Error while repo command : " + str(er))
- await eor(e, REPOMSG)
+ await e.eor(REPOMSG)
@ultroid_cmd(pattern="ultroid$")
diff --git a/plugins/_userlogs.py b/plugins/_userlogs.py
index 191f4350ac34e7e30e06f11b6532efb3c21203cd..ef8dda7a24c940221e0c6d7ef05cce8fded0ac75 100644
--- a/plugins/_userlogs.py
+++ b/plugins/_userlogs.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -11,15 +11,19 @@ import re
from pyUltroid.dB.botchat_db import tag_add, who_tag
from telethon.errors.rpcerrorlist import (
ChatWriteForbiddenError,
+ MediaCaptionTooLongError,
MediaEmptyError,
+ MessageTooLongError,
PeerIdInvalidError,
UserNotParticipantError,
)
+from telethon.tl.types import MessageEntityMention, MessageEntityMentionName
from telethon.utils import get_display_name
from . import *
CACHE_SPAM = {}
+TAG_EDITS = {}
@ultroid_bot.on(
@@ -29,51 +33,55 @@ CACHE_SPAM = {}
),
)
async def all_messages_catcher(e):
- if not udB.get("TAG_LOG"):
+ x = await e.get_sender()
+ if isinstance(x, types.User) and (x.bot or x.verified):
+ return
+ if not udB.get_key("TAG_LOG"):
return
try:
- NEEDTOLOG = int(udB.get("TAG_LOG"))
+ NEEDTOLOG = int(udB.get_key("TAG_LOG"))
except Exception:
return LOGS.info(get_string("userlogs_1"))
- x = await e.get_sender()
- if isinstance(x, types.User) and (x.bot or x.verified):
- return
- y = e.chat
- where_n = get_display_name(y)
- who_n = get_display_name(x)
- where_l = e.message.message_link
- buttons = [[Button.url(where_n, where_l)]]
- if hasattr(x, "username") and x.username:
- who_l = f"https://t.me/{x.username}"
- buttons.append([Button.url(who_n, who_l)])
- else:
- buttons.append([Button.inline(who_n, data=f"who{x.id}")])
+ buttons = await parse_buttons(e)
try:
sent = await asst.send_message(NEEDTOLOG, e.message, buttons=buttons)
+ if TAG_EDITS.get(e.chat_id):
+ TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id}})
+ else:
+ TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id}}})
tag_add(sent.id, e.chat_id, e.id)
except MediaEmptyError:
try:
msg = await asst.get_messages(e.chat_id, ids=e.id)
sent = await asst.send_message(NEEDTOLOG, msg, buttons=buttons)
+ if TAG_EDITS.get(e.chat_id):
+ TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id}})
+ else:
+ TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id}}})
tag_add(sent.id, e.chat_id, e.id)
except Exception as me:
- LOGS.info(me)
+ if not isinstance(me, (PeerIdInvalidError, ValueError)):
+ LOGS.exception(me)
if e.photo or e.sticker or e.gif:
try:
media = await e.download_media()
- await asst.send_message(
+ sent = await asst.send_message(
NEEDTOLOG, e.message.text, file=media, buttons=buttons
)
+ if TAG_EDITS.get(e.chat_id):
+ TAG_EDITS[e.chat_id].update({e.id: {"id": sent.id}})
+ else:
+ TAG_EDITS.update({e.chat_id: {e.id: {"id": sent.id}}})
return os.remove(media)
except Exception as er:
- LOGS.info(er)
+ LOGS.exception(er)
await asst.send_message(NEEDTOLOG, get_string("com_4"), buttons=buttons)
except (PeerIdInvalidError, ValueError):
try:
CACHE_SPAM[NEEDTOLOG]
except KeyError:
await asst.send_message(
- int(udB.get("LOG_CHANNEL")), get_string("userlogs_1")
+ udB.get_key("LOG_CHANNEL"), get_string("userlogs_1")
)
CACHE_SPAM.update({NEEDTOLOG: True})
except ChatWriteForbiddenError:
@@ -88,14 +96,83 @@ async def all_messages_catcher(e):
await asst.send_message(LOG_CHANNEL, MSG)
CACHE_SPAM.update({NEEDTOLOG: True})
except Exception as er:
- LOGS.info(str(er))
+ LOGS.exception(er)
+
+if udB.get_key("TAG_LOG"):
-if udB.get("TAG_LOG"):
+ @ultroid_bot.on(events.MessageEdited(func=lambda x: not x.out))
+ async def upd_edits(event):
+ x = event.sender
+ if isinstance(x, types.User) and (x.bot or x.verified):
+ return
+ if event.chat_id not in TAG_EDITS:
+ if event.sender_id == udB.get_key("TAG_LOG"):
+ return
+ entities = event.get_entities_text()
+ if entities:
+ is_self = False
+ username = event.client.me.username
+ if username:
+ username = username.lower()
+ for ent, text in entities:
+ if isinstance(ent, MessageEntityMention):
+ is_self = text[1:].lower() == username
+ elif isinstance(ent, MessageEntityMentionName):
+ is_self = ent.user_id == event.client.me.id
+ if is_self:
+ text = f"**#Edited & #Mentioned**\n\n{event.text}"
+ try:
+ sent = await asst.send_message(
+ udB.get_key("TAG_LOG"),
+ text,
+ buttons=await parse_buttons(event),
+ )
+ except Exception as er:
+ return LOGS.exception(er)
+ if TAG_EDITS.get(event.chat_id):
+ TAG_EDITS[event.chat_id].update({event.id: {"id": sent.id}})
+ else:
+ TAG_EDITS.update({event.chat_id: {event.id: {"id": sent.id}}})
+ return
+ d_ = TAG_EDITS[event.chat_id]
+ if not d_.get(event.id):
+ return
+ d_ = d_[event.id]
+ msg = None
+ if d_.get("count"):
+ d_["count"] += 1
+ else:
+ msg = True
+ d_.update({"count": 1})
+ if d_["count"] > 10:
+ return # some limit to take edits
+ try:
+ MSG = await asst.get_messages(udB.get_key("TAG_LOG"), ids=d_["id"])
+ except Exception as er:
+ return LOGS.exception(er)
+ TEXT = MSG.text
+ if msg:
+ TEXT += "\n\n🖋 **Later Edited to !**"
+ strf = event.edit_date.strftime("%H:%M:%S")
+ if "\n" not in event.text:
+ TEXT += f"\n• `{strf}` : {event.text}"
+ else:
+ TEXT += f"\n• `{strf}` :\n-> {event.text}"
+ if d_["count"] == 10:
+ TEXT += "\n\n• __Only the first 10 Edits are shown.__"
+ try:
+ await MSG.edit(TEXT, buttons=await parse_buttons(event))
+ except (MessageTooLongError, MediaCaptionTooLongError):
+ del TAG_EDITS[event.chat_id][event.id]
+ except Exception as er:
+ LOGS.exception(er)
@ultroid_bot.on(
events.NewMessage(
- outgoing=True, chats=[int(udB["TAG_LOG"])], func=lambda e: e.reply_to
+ outgoing=True,
+ chats=[udB.get_key("TAG_LOG")],
+ func=lambda e: e.reply_to,
)
)
async def idk(e):
@@ -104,85 +181,92 @@ if udB.get("TAG_LOG"):
if chat and msg:
try:
await ultroid_bot.send_message(chat, e.message, reply_to=msg)
- except BaseException:
- pass
-
-
-@callback(re.compile("who(.*)"))
-async def _(e):
- wah = e.pattern_match.group(1).decode("UTF-8")
- y = await ultroid_bot.get_entity(int(wah))
- who = f"[{get_display_name(y)}](tg://user?id={y.id})"
- x = await e.reply(f"Mention By user : {who}")
- await asyncio.sleep(6)
- await x.delete()
-
-
-# log for assistant
-@asst.on(events.ChatAction)
-async def when_asst_added_to_chat(event):
- if not event.user_added:
- return
- user = await event.get_user()
- chat = await event.get_chat()
- if hasattr(chat, "username") and chat.username:
- chat = f"[{chat.title}](https://t.me/{chat.username}/{event.action_message.id})"
- else:
- chat = f"[{chat.title}](https://t.me/c/{chat.id}/{event.action_message.id})"
- if not (user and user.is_self):
- return
- tmp = event.added_by
- buttons = Button.inline(
- get_string("userlogs_3"), data=f"leave_ch_{event.chat_id}|bot"
- )
- await asst.send_message(
- int(udB.get("LOG_CHANNEL")),
- f"#ADD_LOG\n\n[{tmp.first_name}](tg://user?id={tmp.id}) added [{user.first_name}](tg://user?id={user.id}) to {chat}.",
- buttons=buttons,
- )
+ except BaseException as er:
+ LOGS.exception(er)
-# log for user's new joins
+# log for assistant/user joins/add
-@ultroid_bot.on(events.ChatAction)
-async def when_ultd_added_to_chat(event):
+async def when_added_or_joined(event):
user = await event.get_user()
chat = await event.get_chat()
if not (user and user.is_self):
return
- if hasattr(chat, "username") and chat.username:
+ if getattr(chat, "username", None):
chat = f"[{chat.title}](https://t.me/{chat.username}/{event.action_message.id})"
else:
chat = f"[{chat.title}](https://t.me/c/{chat.id}/{event.action_message.id})"
+ key = "bot" if event.client._bot else "user"
buttons = Button.inline(
- get_string("userlogs_3"), data=f"leave_ch_{event.chat_id}|user"
+ get_string("userlogs_3"), data=f"leave_ch_{event.chat_id}|{key}"
)
if event.user_added:
tmp = event.added_by
text = f"#ADD_LOG\n\n{inline_mention(tmp)} just added {inline_mention(user)} to {chat}."
- elif event.user_joined:
- text = f"#JOIN_LOG\n\n[{user.first_name}](tg://user?id={user.id}) just joined {chat}."
+ elif event.from_request:
+ text = f"#APPROVAL_LOG\n\n{inline_mention(user)} just got Chat Join Approval to {chat}."
else:
- return
- await asst.send_message(int(udB["LOG_CHANNEL"]), text, buttons=buttons)
+ text = f"#JOIN_LOG\n\n{inline_mention(user)} just joined {chat}."
+ await asst.send_message(int(udB.get_key("LOG_CHANNEL")), text, buttons=buttons)
+
+
+asst.add_event_handler(
+ when_added_or_joined, events.ChatAction(func=lambda x: x.user_added)
+)
+ultroid_bot.add_event_handler(
+ when_added_or_joined,
+ events.ChatAction(func=lambda x: x.user_added or x.user_joined),
+)
+
+_client = {"bot": asst, "user": ultroid_bot}
@callback(
re.compile(
"leave_ch_(.*)",
),
- owner=True,
+ from_users=[ultroid_bot.uid],
)
async def leave_ch_at(event):
cht = event.data_match.group(1).decode("UTF-8")
ch_id, client = cht.split("|")
- if client == "bot":
- client = asst
- elif client == "user":
- client = ultroid_bot
- else:
+ try:
+ client = _client[client]
+ except KeyError:
return
name = (await client.get_entity(int(ch_id))).title
await client.delete_dialog(int(ch_id))
await event.edit(get_string("userlogs_5").format(name))
+
+
+@callback("do_nothing")
+async def _(event):
+ await event.answer()
+
+
+async def parse_buttons(event):
+ y, x = event.chat, event.sender
+ where_n, who_n = get_display_name(y), get_display_name(x)
+ where_l = event.message_link
+ buttons = [[Button.url(where_n, where_l)]]
+ if isinstance(x, types.User) and x.username:
+ try:
+ buttons.append(
+ [Button.mention(who_n, await asst.get_input_entity(x.username))]
+ )
+ except Exception as er:
+ LOGS.exception(er)
+ buttons.append([Button.url(who_n, f"t.me/{x.username}")])
+ elif getattr(x, "username"):
+ buttons.append([Button.url(who_n, f"t.me/{x.username}")])
+ else:
+ buttons.append([Button.url(who_n, where_l)])
+ replied = await event.get_reply_message()
+ if replied and replied.out:
+ button = Button.url("Replied to", replied.message_link)
+ if len(who_n) > 7:
+ buttons.append([button])
+ else:
+ buttons[-1].append(button)
+ return buttons
diff --git a/plugins/_wspr.py b/plugins/_wspr.py
index 170f33370e7a74472c639490c6e225ff7923ac67..4fc3d973bd9937d8ceb788d3c88d665801cfc691 100644
--- a/plugins/_wspr.py
+++ b/plugins/_wspr.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -8,18 +8,25 @@
import re
from telethon import Button
-from telethon.errors.rpcerrorlist import BotInlineDisabledError as dis
-from telethon.errors.rpcerrorlist import BotResponseTimeoutError as rep
-from telethon.errors.rpcerrorlist import MessageNotModifiedError as np
+from telethon.errors.rpcerrorlist import (
+ BotInlineDisabledError,
+ BotResponseTimeoutError,
+ MessageNotModifiedError,
+)
+from telethon.tl import types
from telethon.tl.functions.users import GetFullUserRequest as gu
-from telethon.tl.types import UserStatusEmpty as mt
-from telethon.tl.types import UserStatusLastMonth as lm
-from telethon.tl.types import UserStatusLastWeek as lw
-from telethon.tl.types import UserStatusOffline as off
-from telethon.tl.types import UserStatusOnline as on
-from telethon.tl.types import UserStatusRecently as rec
-from . import *
+from . import (
+ HNDLR,
+ LOGS,
+ asst,
+ callback,
+ get_string,
+ in_pattern,
+ inline_mention,
+ ultroid_bot,
+ ultroid_cmd,
+)
buddhhu = {}
@@ -38,16 +45,15 @@ async def _(e):
if put:
try:
results = await e.client.inline_query(asst.me.username, f"msg {put}")
- except rep:
- return await eor(
- e,
+ except BotResponseTimeoutError:
+ return await e.eor(
get_string("help_2").format(HNDLR),
)
- except dis:
- return await eor(e, get_string("help_3"))
+ except BotInlineDisabledError:
+ return await e.eor(get_string("help_3"))
await results[0].click(e.chat_id, reply_to=e.reply_to_msg_id, hide_via=True)
return await e.delete()
- await eor(e, get_string("wspr_3"))
+ await e.eor(get_string("wspr_3"))
@in_pattern("wspr", owner=True)
@@ -102,34 +108,31 @@ async def _(e):
if query.isdigit():
query = int(query)
logi = await ultroid_bot(gu(id=query))
- name = logi.user.first_name
- ids = logi.user.id
- username = logi.user.username
- mention = f"[{name}](tg://user?id={ids})"
- x = logi.user.status
- bio = logi.about
- if isinstance(x, on):
+ user = logi.users[0]
+ mention = inline_mention(user)
+ x = user.status
+ if isinstance(x, types.UserStatusOnline):
status = "Online"
- if isinstance(x, off):
+ elif isinstance(x, types.UserStatusOffline):
status = "Offline"
- if isinstance(x, rec):
+ elif isinstance(x, types.UserStatusRecently):
status = "Last Seen Recently"
- if isinstance(x, lm):
+ elif isinstance(x, types.UserStatusLastMonth):
status = "Last seen months ago"
- if isinstance(x, lw):
+ elif isinstance(x, types.UserStatusLastWeek):
status = "Last seen weeks ago"
- if isinstance(x, mt):
+ else:
status = "Can't Tell"
- text = f"**Name:** `{name}`\n"
- text += f"**Id:** `{ids}`\n"
- if username:
- text += f"**Username:** `{username}`\n"
- url = f"https://t.me/{username}"
+ text = f"**Name:** `{user.first_name}`\n"
+ text += f"**Id:** `{user.id}`\n"
+ if user.username:
+ text += f"**Username:** `{user.username}`\n"
+ url = f"https://t.me/{user.username}"
else:
text += f"**Mention:** `{mention}`\n"
- url = f"tg://user?id={ids}"
+ url = f"tg://user?id={user.id}"
text += f"**Status:** `{status}`\n"
- text += f"**About:** `{bio}`"
+ text += f"**About:** `{logi.full_user.about}`"
button = [
Button.url("Private", url=url),
Button.switch_inline(
@@ -139,7 +142,7 @@ async def _(e):
),
]
sur = e.builder.article(
- title=f"{name}",
+ title=user.first_name,
description=desc,
text=text,
buttons=button,
@@ -150,7 +153,8 @@ async def _(e):
description="You Didn't Type Username or id.",
text="You Didn't Type Username or id.",
)
- except BaseException:
+ except BaseException as er:
+ LOGS.exception(er)
name = get_string("wspr_4").format(query)
sur = e.builder.article(
title=name,
@@ -184,7 +188,7 @@ async def _(e):
buddhhu.pop(ids)
try:
await e.edit(get_string("wspr_2"))
- except np:
+ except MessageNotModifiedError:
pass
else:
await e.answer(get_string("wspr_5"), alert=True)
diff --git a/plugins/admintools.py b/plugins/admintools.py
index 8bae7fb0990c1e80121bd8f9480641596f57c2da..c3a0dacc11c6c258f376f00e545222a2588ceec6 100644
--- a/plugins/admintools.py
+++ b/plugins/admintools.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -45,10 +45,7 @@ from pyUltroid.dB import DEVLIST
from pyUltroid.functions.admins import ban_time
from telethon.errors import BadRequestError
from telethon.errors.rpcerrorlist import ChatNotModifiedError, UserIdInvalidError
-from telethon.tl.functions.channels import (
- DeleteUserHistoryRequest,
- GetFullChannelRequest,
-)
+from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.messages import GetFullChatRequest, SetHistoryTTLRequest
from telethon.tl.types import InputMessagesFilterPinned
@@ -59,7 +56,6 @@ from . import (
eor,
get_string,
get_uinfo,
- get_user_id,
inline_mention,
types,
ultroid_bot,
@@ -67,9 +63,11 @@ from . import (
)
-@ultroid_cmd(pattern="promote ?(.*)", admins_only=True, type=["official", "manager"])
+@ultroid_cmd(
+ pattern="promote ?(.*)", admins_only=True, manager=True, require="add_admins"
+)
async def prmte(ult):
- xx = await eor(ult, get_string("com_1"))
+ xx = await ult.eor(get_string("com_1"))
await ult.get_chat()
user, rank = await get_uinfo(ult)
rank = rank or "Admin"
@@ -94,12 +92,10 @@ async def prmte(ult):
@ultroid_cmd(
- pattern="demote ?(.*)",
- admins_only=True,
- type=["official", "manager"],
+ pattern="demote ?(.*)", admins_only=True, manager=True, require="add_admins"
)
async def dmote(ult):
- xx = await eor(ult, get_string("com_1"))
+ xx = await ult.eor(get_string("com_1"))
await ult.get_chat()
user, rank = await get_uinfo(ult)
if not rank:
@@ -125,10 +121,14 @@ async def dmote(ult):
@ultroid_cmd(
pattern="ban ?(.*)",
admins_only=True,
- type=["official", "manager"],
+ manager=True,
+ require="ban_users",
)
async def bban(ult):
- user, reason = await get_uinfo(ult)
+ something = await get_uinfo(ult)
+ if not something:
+ return
+ user, reason = something
if not user:
return await eod(ult, get_string("ban_1"))
if user.id in DEVLIST:
@@ -147,16 +147,15 @@ async def bban(ult):
await eod(ult, text)
-@ultroid_cmd(
- pattern="unban ?(.*)",
- admins_only=True,
- type=["official", "manager"],
-)
+@ultroid_cmd(pattern="unban ?(.*)", admins_only=True, manager=True, require="ban_users")
async def uunban(ult):
- xx = await eor(ult, get_string("com_1"))
+ xx = await ult.eor(get_string("com_1"))
if ult.text[1:].startswith("unbanall"):
return
- user, reason = await get_uinfo(ult)
+ something = await get_uinfo(ult)
+ if not something:
+ return
+ user, reason = something
if not user:
return await xx.edit(get_string("unban_1"))
try:
@@ -166,7 +165,7 @@ async def uunban(ult):
except UserIdInvalidError:
await xx.edit(get_string("adm_1"))
sender = inline_mention(await ult.get_sender())
- text = get_string("unban_3").format(user, sender, ult.chat.title)
+ text = get_string("unban_3").format(inline_mention(user), sender, ult.chat.title)
if reason:
text += get_string("ban_5").format(reason)
await xx.edit(text)
@@ -174,20 +173,23 @@ async def uunban(ult):
@ultroid_cmd(
pattern="kick ?(.*)",
- admins_only=True,
- type=["official", "manager"],
+ manager=True,
+ require="ban_users",
)
async def kck(ult):
if "kickme" in ult.text:
return
ml = ult.text.split(" ", maxsplit=1)[0]
- xx = await eor(ult, get_string("com_1"))
- user, reason = await get_uinfo(ult)
+ xx = await ult.eor(get_string("com_1"))
+ something = await get_uinfo(ult)
+ if not something:
+ return
+ user, reason = something
if not user:
return await xx.edit(get_string("adm_1"))
if user.id in DEVLIST:
return await xx.edit(get_string("kick_2"))
- if user.is_self:
+ if getattr(user, "is_self", False):
return await xx.edit(get_string("kick_3"))
try:
await ult.client.kick_participant(ult.chat_id, user.id)
@@ -204,42 +206,41 @@ async def kck(ult):
await xx.edit(text)
-@ultroid_cmd(pattern="tban ?(.*)", type=["official", "manager"])
+@ultroid_cmd(pattern="tban ?(.*)", manager=True, require="ban_users")
async def tkicki(e):
huh = e.text.split(" ")
+ inputt = None
try:
tme = huh[1]
except IndexError:
- return await eor(e, get_string("adm_3"), time=15)
+ return await e.eor(get_string("adm_3"), time=15)
try:
inputt = huh[2]
except IndexError:
- pass
- chat = await e.get_chat()
- if e.is_reply:
- replied = await e.get_reply_message()
- userid = replied.sender_id
- fn = (await e.get_sender()).first_name
- elif inputt:
- userid = await get_user_id(inputt)
- fn = (await e.client.get_entity(userid)).first_name
- else:
- return await eor(e, get_string("tban_1"), time=3)
+ if e.reply_to_msg_id:
+ inputt = (await e.get_reply_message()).sender_id
+ if not inputt:
+ return await e.eor(get_string("tban_1"))
+ userid = await e.client.parse_id(inputt)
+ try:
+ user = await e.client.get_entity(userid)
+ except Exception as ex:
+ return await eor(d, f"`{ex}`")
try:
bun = await ban_time(e, tme)
await e.client.edit_permissions(
- e.chat_id, userid, until_date=bun, view_messages=False
+ e.chat_id, user.id, until_date=bun, view_messages=False
)
await eod(
e,
- get_string("tban_2").format(fn, chat.title, tme),
+ get_string("tban_2").format(inline_mention(user), e.chat.title, tme),
time=15,
)
except Exception as m:
- return await eor(e, str(m))
+ return await e.eor(str(m))
-@ultroid_cmd(pattern="pin$", type=["official", "manager"])
+@ultroid_cmd(pattern="pin$", manager=True, require="pin_messages")
async def pin(msg):
if not msg.is_reply:
return await eor(msg, get_string("pin_1"))
@@ -259,10 +260,11 @@ async def pin(msg):
@ultroid_cmd(
pattern="unpin($| (.*))",
- type=["official", "manager"],
+ manager=True,
+ require="pin_messages",
)
async def unp(ult):
- xx = await eor(ult, get_string("com_1"))
+ xx = await ult.eor(get_string("com_1"))
ch = (ult.pattern_match.group(1)).strip()
msg = None
if ult.is_reply:
@@ -278,10 +280,7 @@ async def unp(ult):
await xx.edit("`Unpinned!`")
-@ultroid_cmd(
- pattern="purge ?(.*)",
- type=["official", "manager"],
-)
+@ultroid_cmd(pattern="purge ?(.*)", manager=True, require="delete_messages")
async def fastpurger(purg):
match = purg.pattern_match.group(1)
try:
@@ -290,7 +289,10 @@ async def fastpurger(purg):
ABC = None
if ABC and purg.text[6] in ["m", "a"]:
return
- if not purg._client._bot and ((match) or (purg.is_reply and purg.is_private)):
+ if not purg._client._bot and (
+ (match)
+ or (purg.is_reply and (purg.is_private or isinstance(purg.chat, types.Chat)))
+ ):
p = 0
async for msg in purg.client.iter_messages(
purg.chat_id,
@@ -304,8 +306,9 @@ async def fastpurger(purg):
return await eor(purg, get_string("purge_1"), time=10)
try:
await purg.client.delete_messages(
- purg.chat_id, [a for a in range(purg.reply_to_msg_id, purg.id + 1)]
+ purg.chat_id, list(range(purg.reply_to_msg_id, purg.id + 1))
)
+
except Exception as er:
LOGS.info(er)
await purg.respond(
@@ -371,15 +374,16 @@ async def _(e):
get_string("purgeall_1"),
)
- name = (await e.get_reply_message()).sender
+ msg = await e.get_reply_message()
+ name = msg.sender
try:
- await e.client(DeleteUserHistoryRequest(e.chat_id, name.id))
- await eor(e, get_string("purgeall_2").format(name.first_name), time=5)
+ await e.client.delete_messages(e.chat_id, from_user=msg.sender_id)
+ await e.eor(get_string("purgeall_2").format(name.first_name), time=5)
except Exception as er:
- return await eor(e, str(er), time=5)
+ return await e.eor(str(er), time=5)
-@ultroid_cmd(pattern="pinned", type=["official", "manager"], groups_only=True)
+@ultroid_cmd(pattern="pinned", manager=True, groups_only=True)
async def djshsh(event):
chat = await event.get_chat()
if isinstance(chat, types.Chat):
@@ -390,19 +394,17 @@ async def djshsh(event):
return
msg_id = FChat.full_chat.pinned_msg_id
if not msg_id:
- return await eor(event, get_string("pinned_1"))
+ return await event.eor(get_string("pinned_1"))
msg = await event.client.get_messages(chat.id, ids=msg_id)
if msg:
- await eor(
- event, f"Pinned Message in Current chat is [here]({msg.message_link})."
- )
+ await event.eor(get_string("pinned_2").format(msg.message_link))
@ultroid_cmd(
pattern="listpinned$",
)
async def get_all_pinned(event):
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
chat_id = (str(event.chat_id)).replace("-100", "")
chat_name = (await event.get_chat()).title
a = ""
@@ -411,7 +413,7 @@ async def get_all_pinned(event):
event.chat_id, filter=InputMessagesFilterPinned
):
if i.message:
- t = " ".join(i.message.split()[0:4])
+ t = " ".join(i.message.split()[:4])
txt = "{}....".format(t)
else:
txt = "Go to message."
@@ -436,7 +438,7 @@ async def get_all_pinned(event):
async def autodelte(ult):
match = ult.pattern_match.group(1)
if not match or match not in ["24h", "7d", "1m", "off"]:
- return await eor(ult, "`Please Use in Proper Format..`", time=5)
+ return await ult.eor("`Please Use in Proper Format..`", time=5)
if match == "24h":
tt = 3600 * 24
elif match == "7d":
@@ -451,4 +453,4 @@ async def autodelte(ult):
return await eor(
ult, f"Auto Delete Setting is Already same to `{match}`", time=5
)
- await eor(ult, f"Auto Delete Status Changed to `{match}` !")
+ await ult.eor(f"Auto Delete Status Changed to `{match}` !")
diff --git a/plugins/afk.py b/plugins/afk.py
index bd0fa1c326a35246b193d60da5ec11f11dcdd53c..c41e1d8c4f3c887b336f8fcd9f00508a82af05b4 100644
--- a/plugins/afk.py
+++ b/plugins/afk.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -27,9 +27,9 @@ from . import (
NOSPAM_CHAT,
Redis,
asst,
- eor,
get_string,
mediainfo,
+ udB,
ultroid_bot,
ultroid_cmd,
)
@@ -39,9 +39,7 @@ old_afk_msg = []
@ultroid_cmd(pattern="afk ?(.*)", fullsudo=True)
async def set_afk(event):
- if event.client._bot:
- await eor(event, "Master, I am a Bot, I cant go AFK..")
- elif is_afk():
+ if event.client._bot or is_afk():
return
text, media, media_type = None, None, None
if event.pattern_match.group(1):
@@ -56,12 +54,17 @@ async def set_afk(event):
file = await event.client.download_media(reply.media)
iurl = uf(file)
media = f"https://telegra.ph{iurl[0]}"
- elif "sticker" or "audio" in media_type:
- media = reply.file.id
else:
- return await eor(event, get_string("com_4"), time=5)
- await eor(event, "`Done`", time=2)
+ media = reply.file.id
+ await event.eor("`Done`", time=2)
add_afk(text, media_type, media)
+ ultroid_bot.add_handler(remove_afk, events.NewMessage(outgoing=True))
+ ultroid_bot.add_handler(
+ on_afk,
+ events.NewMessage(
+ incoming=True, func=lambda e: bool(e.mentioned or e.is_private)
+ ),
+ )
msg1, msg2 = None, None
if text and media:
if "sticker" in media_type:
@@ -92,16 +95,13 @@ async def set_afk(event):
await asst.send_message(LOG_CHANNEL, msg1.text)
-@ultroid_bot.on(events.NewMessage(outgoing=True))
async def remove_afk(event):
- if (
- event.is_private
- and Redis("PMSETTING") == "True"
- and not is_approved(event.chat_id)
- ):
+ if event.is_private and udB.get_key("PMSETTING") and not is_approved(event.chat_id):
return
elif "afk" in event.text.lower():
return
+ elif event.chat_id in NOSPAM_CHAT:
+ return
if is_afk():
_, _, _, afk_time = is_afk()
del_afk()
@@ -116,15 +116,8 @@ async def remove_afk(event):
await off.delete()
-@ultroid_bot.on(
- events.NewMessage(incoming=True, func=lambda e: bool(e.mentioned or e.is_private)),
-)
async def on_afk(event):
- if (
- event.is_private
- and Redis("PMSETTING") == "True"
- and not is_approved(event.chat_id)
- ):
+ if event.is_private and Redis("PMSETTING") and not is_approved(event.chat_id):
return
elif "afk" in event.text.lower():
return
@@ -163,3 +156,13 @@ async def on_afk(event):
old_afk_msg.append(msg1)
if msg2:
old_afk_msg.append(msg2)
+
+
+if udB.get_key("AFK_DB"):
+ ultroid_bot.add_handler(remove_afk, events.NewMessage(outgoing=True))
+ ultroid_bot.add_handler(
+ on_afk,
+ events.NewMessage(
+ incoming=True, func=lambda e: bool(e.mentioned or e.is_private)
+ ),
+ )
diff --git a/plugins/akinator.py b/plugins/akinator.py
deleted file mode 100644
index 8d6ced5add7d4b1dab3619835b3f8e83d6ee955b..0000000000000000000000000000000000000000
--- a/plugins/akinator.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
-#
-# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
-# PLease read the GNU Affero General Public License in
-# .
-"""
-✘ Commands Available -
-
-• `{i}akinator`
- `Start Akinator Game`.
-
-"""
-
-import re
-
-import akinator
-from telethon.errors import BotMethodInvalidError
-
-from . import Button, asst, callback, get_string, in_pattern, types, ultroid_cmd
-
-games = {}
-aki_photo = "https://telegra.ph/file/b0ff07069e8637783fdae.jpg"
-
-
-@ultroid_cmd(pattern="akinator")
-async def doit(e):
- sta = akinator.Akinator()
- games.update({e.chat_id: {e.id: sta}})
- try:
- m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}")
- await m[0].click(e.chat_id)
- except BotMethodInvalidError:
- return await asst.send_file(
- e.chat_id,
- aki_photo,
- buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"),
- )
- if e.out:
- await e.delete()
-
-
-@callback(re.compile("aki_?(.*)"), owner=True)
-async def doai(e):
- adt = e.pattern_match.group(1).decode("utf-8")
- dt = adt.split("_")
- ch = int(dt[0])
- mid = int(dt[1])
- await e.edit(get_string("com_1"))
- try:
- qu = games[ch][mid].start_game(child_mode=True)
- # child mode should be promoted
- except KeyError:
- return await e.answer(get_string("aki_1"), alert=True)
- bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]]
- cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]]
-
- bts = [bts, cts]
- # ignored Back Button since it makes the Pagination looks Bad
- await e.edit("Q. " + qu, buttons=bts)
-
-
-@callback(re.compile("aka_?(.*)"), owner=True)
-async def okah(e):
- mk = e.pattern_match.group(1).decode("utf-8").split("_")
- ch = int(mk[0])
- mid = int(mk[1])
- ans = mk[2]
- try:
- gm = games[ch][mid]
- except KeyError:
- await e.answer(get_string("aki_3"))
- return
- text = gm.answer(ans)
- if gm.progression >= 80:
- gm.win()
- gs = gm.first_guess
- text = "It's " + gs["name"] + "\n " + gs["description"]
- return await e.edit(text, file=gs["absolute_picture_path"])
- bts = [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]]
- cts = [
- Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]
- ]
-
- bts = [bts, cts]
- await e.edit(text, buttons=bts)
-
-
-@in_pattern(re.compile("aki_?(.*)"), owner=True)
-async def eiagx(e):
- bts = Button.inline(get_string("aki_2"), data=e.text)
- ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", [])
- ans = [
- await e.builder.article(
- "Akinator",
- type="photo",
- content=ci,
- text="Akinator",
- thumb=ci,
- buttons=bts,
- include_media=True,
- )
- ]
- await e.answer(ans)
diff --git a/plugins/antiflood.py b/plugins/antiflood.py
index 7eabcafcc504ad7c41bcba1dc266364eabc4b04f..79ffd9f214834074b378b1edb1f5bfb4217b7b7b 100644
--- a/plugins/antiflood.py
+++ b/plugins/antiflood.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -24,21 +24,11 @@ from pyUltroid.dB.antiflood_db import get_flood, get_flood_limit, rem_flood, set
from pyUltroid.functions.admins import admin_check
from telethon.events import NewMessage as NewMsg
-from . import (
- Button,
- Redis,
- asst,
- callback,
- eod,
- eor,
- get_string,
- ultroid_bot,
- ultroid_cmd,
-)
+from . import Button, Redis, asst, callback, eod, get_string, ultroid_bot, ultroid_cmd
_check_flood = {}
-if Redis("ANTIFLOOD") is not (None or ""):
+if Redis("ANTIFLOOD"):
@ultroid_bot.on(
NewMsg(
@@ -49,14 +39,14 @@ if Redis("ANTIFLOOD") is not (None or ""):
count = 1
chat = (await event.get_chat()).title
if event.chat_id in _check_flood.keys():
- if event.sender_id == [x for x in _check_flood[event.chat_id].keys()][0]:
+ if event.sender_id == list(_check_flood[event.chat_id].keys())[0]:
count = _check_flood[event.chat_id][event.sender_id]
_check_flood[event.chat_id] = {event.sender_id: count + 1}
else:
_check_flood[event.chat_id] = {event.sender_id: count}
else:
_check_flood[event.chat_id] = {event.sender_id: count}
- if await admin_check(event) or event.sender.bot:
+ if await admin_check(event, silent=True) or event.sender.bot:
return
if event.sender_id in DEVLIST:
return
@@ -105,9 +95,9 @@ async def unmuting(e):
async def setflood(e):
input_ = e.pattern_match.group(1)
if not input_:
- return await eor(e, "`What?`", time=5)
+ return await e.eor("`What?`", time=5)
if not input_.isdigit():
- return await eor(e, get_string("com_3"), time=5)
+ return await e.eor(get_string("com_3"), time=5)
m = set_flood(e.chat_id, input_)
if m:
return await eod(e, get_string("antiflood_4").format(input_))
@@ -124,8 +114,8 @@ async def remove_flood(e):
except BaseException:
pass
if hmm:
- return await eor(e, get_string("antiflood_1"), time=5)
- await eor(e, get_string("antiflood_2"), time=5)
+ return await e.eor(get_string("antiflood_1"), time=5)
+ await e.eor(get_string("antiflood_2"), time=5)
@ultroid_cmd(
@@ -135,5 +125,5 @@ async def remove_flood(e):
async def getflood(e):
ok = get_flood_limit(e.chat_id)
if ok:
- return await eor(e, get_string("antiflood_5").format(ok), time=5)
- await eor(e, get_string("antiflood_2"), time=5)
+ return await e.eor(get_string("antiflood_5").format(ok), time=5)
+ await e.eor(get_string("antiflood_2"), time=5)
diff --git a/plugins/asstcmd.py b/plugins/asstcmd.py
index c6d7d6fa05522fa57ac0d42bec6ec3088ee70f6f..18b690ee6a6f85d282caf7a079afa11d4c4a3a09 100644
--- a/plugins/asstcmd.py
+++ b/plugins/asstcmd.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -21,9 +21,9 @@ import os
from pyUltroid.dB.asstcmd_db import *
from pyUltroid.functions.tools import create_tl_btn, format_btn, get_msg_button
from telegraph import upload_file as uf
-from telethon.utils import pack_bot_file_id
+from telethon import events, utils
-from . import asst_cmd, eor, get_string, mediainfo, ultroid_cmd
+from . import asst, get_string, mediainfo, ultroid_cmd
@ultroid_cmd(pattern="addcmd ?(.*)")
@@ -31,7 +31,7 @@ async def ac(e):
wrd = (e.pattern_match.group(1)).lower()
wt = await e.get_reply_message()
if not (wt and wrd):
- return await eor(e, get_string("asstcmd_1"), time=5)
+ return await e.eor(get_string("asstcmd_1"), time=5)
if "/" in wrd:
wrd = wrd.replace("/", "")
btn = format_btn(wt.buttons) if wt.buttons else None
@@ -44,36 +44,42 @@ async def ac(e):
m = "https://telegra.ph" + variable[0]
elif wut == "video":
if wt.media.document.size > 8 * 1000 * 1000:
- return await eor(e, get_string("com_4"), time=5)
+ return await e.eor(get_string("com_4"), time=5)
dl = await e.client.download_media(wt.media)
variable = uf(dl)
os.remove(dl)
m = "https://telegra.ph" + variable[0]
else:
- m = pack_bot_file_id(wt.media)
+ m = utils.pack_bot_file_id(wt.media)
if wt.text:
txt = wt.text
if not btn:
txt, btn = get_msg_button(wt.text)
add_cmd(wrd, txt, m, btn)
else:
- add_cmd(wrd, None, m)
+ add_cmd(wrd, None, m, btn)
else:
txt = wt.text
if not btn:
txt, btn = get_msg_button(wt.text)
add_cmd(wrd, txt, None, btn)
- await eor(e, get_string("asstcmd_4").format(wrd))
+ asst.add_handler(
+ astcmds,
+ events.NewMessage(
+ func=lambda x: x.text.startswith("/") and x.text[1:] in list(list_cmds())
+ ),
+ )
+ await e.eor(get_string("asstcmd_4").format(wrd))
@ultroid_cmd(pattern="remcmd ?(.*)")
async def rc(e):
wrd = (e.pattern_match.group(1)).lower()
if not wrd:
- return await eor(e, get_string("asstcmd_2"), time=5)
+ return await e.eor(get_string("asstcmd_2"), time=5)
wrd = wrd.replace("/", "")
rem_cmd(wrd)
- await eor(e, get_string("asstcmd_3").format(wrd))
+ await e.eor(get_string("asstcmd_3").format(wrd))
@ultroid_cmd(pattern="listcmd$")
@@ -82,15 +88,23 @@ async def lscmd(e):
ok = get_string("asstcmd_6")
for x in list_cmds():
ok += "/" + x + "\n"
- return await eor(e, ok)
- return await eor(e, get_string("asstcmd_5"))
+ return await e.eor(ok)
+ return await e.eor(get_string("asstcmd_5"))
-@asst_cmd(func=lambda x: x.text.startswith("/") and x.text[1:] in list(list_cmds()))
-async def ascmds(e):
+async def astcmds(e):
xx = (e.text.replace("/", "")).lower().split()[0]
if cmd_reply(xx):
msg, media, bt = cmd_reply(xx)
if bt:
bt = create_tl_btn(bt)
await e.reply(msg, file=media, buttons=bt)
+
+
+if udB.get_key("ASST_CMDS"):
+ asst.add_handler(
+ astcmds,
+ events.NewMessage(
+ func=lambda x: x.text.startswith("/") and x.text[1:] in list(list_cmds())
+ ),
+ )
diff --git a/plugins/audiotools.py b/plugins/audiotools.py
index 5de3b8c3931785ee626a39bdd0314ba2faae5d28..4a0d67351b91f4928a91ecdb4be12a6411354fe2 100644
--- a/plugins/audiotools.py
+++ b/plugins/audiotools.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -49,7 +49,7 @@ async def vnc(e):
r = await e.get_reply_message()
if not mediainfo(r.media).startswith(("audio", "video")):
return await eod(e, get_string("spcltool_1"))
- xxx = await eor(e, get_string("com_1"))
+ xxx = await e.eor(get_string("com_1"))
dl = r.file.name
c_time = time.time()
file = await downloader(
@@ -89,7 +89,7 @@ async def trim_aud(e):
name = ""
if not name:
name = dt.now().isoformat("_", "seconds") + ".mp4"
- xxx = await eor(e, get_string("audiotools_5"))
+ xxx = await e.eor(get_string("audiotools_5"))
c_time = time.time()
file = await downloader(
"resources/downloads/" + name,
@@ -144,17 +144,17 @@ async def trim_aud(e):
)
await xxx.delete()
else:
- await eor(e, get_string("audiotools_1"), time=5)
+ await e.eor(get_string("audiotools_1"), time=5)
@ultroid_cmd(pattern="extractaudio$")
async def ex_aud(e):
reply = await e.get_reply_message()
if not (reply and reply.media and mediainfo(reply.media).startswith("video")):
- return await eor(e, get_string("audiotools_8"))
+ return await e.eor(get_string("audiotools_8"))
name = reply.file.name or "video.mp4"
vfile = reply.media.document
- msg = await eor(e, get_string("com_1"))
+ msg = await e.eor(get_string("com_1"))
c_time = time.time()
file = await downloader(
"resources/downloads/" + name,
diff --git a/plugins/autocorrect.py b/plugins/autocorrect.py
index 5d9c89abbaa866bb24ef0bfd9557a67e867f8764..19f121241200cf2e55dfdcf798f7806850707cd8 100644
--- a/plugins/autocorrect.py
+++ b/plugins/autocorrect.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -14,25 +14,30 @@
import string
-from gingerit.gingerit import GingerIt
+from . import HNDLR, eor, get_string, udB, ultroid_bot, ultroid_cmd # ignore: pylint
+
+try:
+ from gingerit.gingerit import GingerIt
+except ImportError:
+ LOGS.info("GingerIt not found")
from google_trans_new import google_translator
from telethon import events
-from . import HNDLR, Redis, eor, get_string, udB, ultroid_bot, ultroid_cmd
-
@ultroid_cmd(pattern="autocorrect", fullsudo=True)
async def acc(e):
if Redis("AUTOCORRECT") != "True":
- udB.set("AUTOCORRECT", "True")
- return await eor(e, get_string("act_1"), time=5)
- udB.delete("AUTOCORRECT")
- await eor(e, get_string("act_2"), time=5)
+ udB.set_key("AUTOCORRECT", "True")
+ ultroid_bot.add_handler(
+ gramme, events.NewMessage(outgoing=True, func=lambda x: x.text)
+ )
+ return await e.eor(get_string("act_1"), time=5)
+ udB.del_key("AUTOCORRECT")
+ await e.eor(get_string("act_2"), time=5)
-@ultroid_bot.on(events.NewMessage(outgoing=True, func=lambda x: x.text))
async def gramme(event):
- if Redis("AUTOCORRECT") != "True":
+ if not udB.get_key("AUTOCORRECT"):
return
t = event.text
if t[0] == HNDLR or t[0].lower() not in string.ascii_lowercase or t.endswith(".."):
@@ -47,3 +52,9 @@ async def gramme(event):
await event.edit(res)
except BaseException:
pass
+
+
+if udB.get_key("AUTOCORRECT"):
+ ultroid_bot.add_handler(
+ gramme, events.NewMessage(outgoing=True, func=lambda x: x.text)
+ )
diff --git a/plugins/autopic.py b/plugins/autopic.py
index f23a283188c13bb109541601b5cff800d3616450..55fb05b56d4c38f10b929022658b3b4210405418 100644
--- a/plugins/autopic.py
+++ b/plugins/autopic.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -10,49 +10,90 @@
• `{i}autopic `
Will change your profile pic at defined intervals with pics related to the given topic.
-• `{i}stoppic`
- Stop the AutoPic command.
-
+• `{i}autopic` : stop autopic if active.
"""
import asyncio
import os
+import random
+from glob import glob
from random import shuffle
-from pyUltroid.functions.misc import unsplashsearch
+from pyUltroid.functions.google_image import googleimagesdownload
from telethon.tl.functions.photos import UploadProfilePhotoRequest
-from . import download_file, eor, get_string, udB, ultroid_cmd
+from . import LOGS, get_string, udB, ultroid_bot, ultroid_cmd
@ultroid_cmd(pattern="autopic ?(.*)")
async def autopic(e):
search = e.pattern_match.group(1)
+ if udB.get_key("AUTOPIC") and not search:
+ udB.del_key("AUTOPIC")
+ return await e.eor(get_string("autopic_5"))
if not search:
- return await eor(e, get_string("autopic_1"), time=5)
- e = await eor(e, get_string("com_1"))
- clls = await unsplashsearch(search, limit=50)
- if not clls:
- return await eor(e, get_string("autopic_2").format(search), time=5)
- await eor(e, get_string("autopic_3").format(search))
- udB.set("AUTOPIC", "True")
- ST = udB.get("SLEEP_TIME")
- SLEEP_TIME = int(ST) if ST else 1221
+ return await e.eor(get_string("autopic_1"), time=5)
+ e = await e.eor(get_string("com_1"))
+ gi = googleimagesdownload()
+ args = {
+ "keywords": search,
+ "limit": 50,
+ "format": "jpg",
+ "output_directory": "./resources/downloads/",
+ }
+ try:
+ pth = await gi.download(args)
+ ok = pth[0][search]
+ except Exception as er:
+ LOGS.exception(er)
+ return await e.eor(str(er))
+ if not ok:
+ return await e.eor(get_string("autopic_2").format(search), time=5)
+ await e.eor(get_string("autopic_3").format(search))
+ udB.set_key("AUTOPIC", search)
+ SLEEP_TIME = udB.get_key("SLEEP_TIME") or 1221
while True:
- for lie in clls:
- if udB.get("AUTOPIC") != "True":
+ for lie in ok:
+ if udB.get_key("AUTOPIC") != search:
return
- kar = await download_file(lie, "autopic.png")
- file = await e.client.upload_file(kar)
+ file = await e.client.upload_file(lie)
await e.client(UploadProfilePhotoRequest(file))
- os.remove(kar)
await asyncio.sleep(SLEEP_TIME)
shuffle(clls)
-@ultroid_cmd(pattern="stoppic$")
-async def stoppo(ult):
- gt = udB.get("AUTOPIC")
- if gt != "True":
- return await eor(ult, get_string("autopic_4"), time=5)
- udB.set("AUTOPIC", "None")
- await eor(ult, get_string("autopic_5"), time=5)
+if search := udB.get_key("AUTOPIC"):
+ gi = googleimagesdownload()
+ args = {
+ "keywords": search,
+ "limit": 50,
+ "format": "jpg",
+ "output_directory": "./resources/downloads/",
+ }
+ images = []
+ if os.path.exists(f"./resources/downloads/{search}"):
+ images = glob(f"resources/downloads/{search}/*")
+ sleep = udB.get_key("SLEEP_TIME") or 1221
+
+ async def autopic_func():
+ if udB.get_key("AUTOPIC") != search:
+ return
+ if not images:
+ try:
+ pth = await gi.download(args)
+ ok = pth[0][search]
+ images.extend(ok)
+ except Exception as er:
+ LOGS.exception(er)
+ return
+ else:
+ ok = images
+ img = random.choice(ok)
+ file = await ultroid_bot.upload_file(img)
+ await ultroid_bot(UploadProfilePhotoRequest(file))
+ shuffle(ok)
+
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
+
+ schedule = AsyncIOScheduler()
+ schedule.add_job(autopic_func, "interval", seconds=sleep)
+ schedule.start()
diff --git a/plugins/blacklist.py b/plugins/blacklist.py
index f16c2fc66b5b6c020842c55fb540d1f0561a59ce..6cf2fe8e81ac70fef05cf241efa3ec09c560bc06 100644
--- a/plugins/blacklist.py
+++ b/plugins/blacklist.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -27,7 +27,7 @@ from pyUltroid.dB.blacklist_db import (
rem_blacklist,
)
-from . import eor, events, get_string, ultroid_bot, ultroid_cmd
+from . import events, get_string, udB, ultroid_bot, ultroid_cmd
@ultroid_cmd(pattern="blacklist ?(.*)", admins_only=True)
@@ -35,12 +35,13 @@ async def af(e):
wrd = e.pattern_match.group(1)
chat = e.chat_id
if not (wrd):
- return await eor(e, get_string("blk_1"), time=5)
+ return await e.eor(get_string("blk_1"), time=5)
wrd = e.text[11:]
heh = wrd.split(" ")
for z in heh:
add_blacklist(int(chat), z.lower())
- await eor(e, get_string("blk_2").format(wrd))
+ ultroid_bot.add_handler(blacklist, events.NewMessage(incoming=True))
+ await e.eor(get_string("blk_2").format(wrd))
@ultroid_cmd(pattern="remblacklist ?(.*)", admins_only=True)
@@ -48,12 +49,12 @@ async def rf(e):
wrd = e.pattern_match.group(1)
chat = e.chat_id
if not wrd:
- return await eor(e, get_string("blk_3"), time=5)
+ return await e.eor(get_string("blk_3"), time=5)
wrd = e.text[14:]
heh = wrd.split(" ")
for z in heh:
rem_blacklist(int(chat), z.lower())
- await eor(e, get_string("blk_4").format(wrd))
+ await e.eor(get_string("blk_4").format(wrd))
@ultroid_cmd(pattern="listblacklist$", admins_only=True)
@@ -61,12 +62,11 @@ async def lsnote(e):
x = list_blacklist(e.chat_id)
if x:
sd = get_string("blk_5")
- return await eor(e, sd + x)
- await eor(e, get_string("blk_6"))
+ return await e.eor(sd + x)
+ await e.eor(get_string("blk_6"))
-@ultroid_bot.on(events.NewMessage(incoming=True))
-async def bl(e):
+async def blacklist(e):
x = get_blacklist(e.chat_id)
if x:
for z in e.text.lower().split():
@@ -77,3 +77,7 @@ async def bl(e):
break
except BaseException:
break
+
+
+if udB.get_key("BLACKLIST_DB"):
+ ultroid_bot.add_handler(blacklist, events.NewMessage(incoming=True))
diff --git a/plugins/bot.py b/plugins/bot.py
index f23cc39f5632ad0c6dfda53b7ea272adea167811..6acddfac016e983388400bc440c42ba920129a5d 100644
--- a/plugins/bot.py
+++ b/plugins/bot.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -7,12 +7,15 @@
"""
✘ Commands Available
-• `{i}alive` | `{i}ialive`
+• `{i}alive` | `{i}alive inline`
Check if your bot is working.
• `{i}ping`
Check Ultroid's response time.
+• `{i}update`
+ See changelogs if any update is available.
+
• `{i}cmds`
View all plugin names.
@@ -21,10 +24,8 @@
• `{i}logs (sys)`
Get the full terminal logs.
-
• `{i}logs carbon`
Get the carbonized sys logs.
-
• `{i}logs heroku`
Get the latest 100 lines of heroku logs.
@@ -40,19 +41,20 @@ from random import choice
from git import Repo
from pyUltroid.version import __version__ as UltVer
from telethon import __version__
-from telethon.errors.rpcerrorlist import ChatSendMediaForbiddenError
+from telethon.errors.rpcerrorlist import (
+ BotMethodInvalidError,
+ ChatSendMediaForbiddenError,
+)
from telethon.utils import resolve_bot_file_id
-try:
- from carbonnow import Carbon
-except ImportError:
- Carbon = None
-
from . import (
ATRA_COL,
+ INLINE_PIC,
LOGS,
OWNER_NAME,
+ ULTROID_IMAGES,
Button,
+ Carbon,
Telegraph,
Var,
allcmds,
@@ -72,8 +74,17 @@ from . import (
udB,
ultroid_cmd,
ultroid_version,
+ updater,
)
+ULTPIC = INLINE_PIC or choice(ULTROID_IMAGES)
+buttons = [
+ [
+ Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"),
+ Button.url(get_string("bot_4"), "t.me/UltroidSupport"),
+ ]
+]
+
# Will move to strings
alive_txt = """
The Ultroid Userbot
@@ -83,6 +94,8 @@ The Ultroid Userbot
◍ Telethon - {}
"""
+in_alive = "{}\n\n🌀 Ultroid Version -> {}
\n🌀 PyUltroid -> {}
\n🌀 Python -> {}
\n🌀 Uptime -> {}
\n🌀 Branch -> [ {} ]\n\n• Join @TheUltroid"
+
@callback("alive")
async def alive(event):
@@ -91,90 +104,92 @@ async def alive(event):
@ultroid_cmd(
- pattern="alive$",
+ pattern="alive ?(.*)",
)
async def lol(ult):
- pic = udB.get("ALIVE_PIC")
+ match = ult.pattern_match.group(1)
+ inline = None
+ if match in ["inline", "i"]:
+ try:
+ res = await ult.client.inline_query(asst.me.username, "alive")
+ return await res[0].click(ult.chat_id)
+ except BotMethodInvalidError:
+ pass
+ except BaseException as er:
+ LOGS.exception(er)
+ inline = True
+ pic = udB.get_key("ALIVE_PIC")
uptime = time_formatter((time.time() - start_time) * 1000)
- header = udB.get("ALIVE_TEXT") or get_string("bot_1")
+ header = udB.get_key("ALIVE_TEXT") or get_string("bot_1")
y = Repo().active_branch
xx = Repo().remotes[0].config_reader.get("url")
rep = xx.replace(".git", f"/tree/{y}")
kk = f" `[{y}]({rep})` "
- als = (get_string("alive_1")).format(
- header,
- OWNER_NAME,
- ultroid_version,
- UltVer,
- uptime,
- pyver(),
- __version__,
- kk,
- )
- if pic is None:
- await eor(ult, als)
- elif "telegra" in pic:
- try:
- await ult.reply(als, file=pic, link_preview=False)
- await ult.delete()
- except ChatSendMediaForbiddenError:
- await eor(ult, als, link_preview=False)
+ if inline:
+ kk = f"{y}"
+ parse = "html"
+ als = in_alive.format(
+ header,
+ ultroid_version,
+ UltVer,
+ pyver(),
+ uptime,
+ kk,
+ )
+ if _e := udB.get_key("ALIVE_EMOJI"):
+ als = als.replace("🌀", _e)
else:
+ parse = "md"
+ als = (get_string("alive_1")).format(
+ header,
+ OWNER_NAME,
+ ultroid_version,
+ UltVer,
+ uptime,
+ pyver(),
+ __version__,
+ kk,
+ )
+ if a := udB.get_key("ALIVE_EMOJI"):
+ als = als.replace("✵", a)
+ if pic:
try:
- await ult.reply(file=pic)
- await ult.reply(als, link_preview=False)
- await ult.delete()
+ await ult.reply(
+ als,
+ file=pic,
+ parse_mode=parse,
+ link_preview=False,
+ buttons=buttons if inline else None,
+ )
+ await ult.try_delete()
except ChatSendMediaForbiddenError:
- await eor(ult, als, link_preview=False)
-
-
-@ultroid_cmd(
- pattern="ialive$",
-)
-async def is_on(ult):
- if not ult.client._bot:
- await ult.delete()
- try:
- res = await ult.client.inline_query(asst.me.username, "alive")
- await res[0].click(ult.chat_id)
- except Exception as er:
- LOGS.info(er)
- return
- pic = udB.get("ALIVE_PIC")
- uptime = time_formatter((time.time() - start_time) * 1000)
- header = udB.get("ALIVE_TEXT") or get_string("bot_1")
- y = Repo().active_branch
- xx = Repo().remotes[0].config_reader.get("url")
- rep = xx.replace(".git", f"/tree/{y}")
- kk = f" `[{y}]({rep})` "
- als = (get_string("alive_1")).format(
- header,
- OWNER_NAME,
- ultroid_version,
- UltVer,
- uptime,
- pyver(),
- __version__,
- kk,
- )
- buttons = [
- [Button.inline(get_string("bot_2"), "alive")],
- [
- Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"),
- Button.url(get_string("bot_4"), "t.me/UltroidSupport"),
- ],
- ]
- await ult.client.send_message(
- ult.chat_id, als, file=pic, buttons=buttons, link_preview=False
+ pass
+ except BaseException as er:
+ LOGS.exception(er)
+ try:
+ await ult.reply(file=pic)
+ await ult.reply(
+ als,
+ parse_mode=parse,
+ buttons=buttons if inline else None,
+ link_preview=False,
+ )
+ return await ult.try_delete()
+ except BaseException as er:
+ LOGS.exception(er)
+ await eor(
+ ult,
+ als,
+ parse_mode=parse,
+ link_preview=False,
+ buttons=buttons if inline else None,
)
@ultroid_cmd(pattern="ping$", chats=[], type=["official", "assistant"])
async def _(event):
- if event.out:
- await event.delete()
start = time.time()
- x = await event.respond("Pong !")
+ x = await event.eor("Pong !")
end = round((time.time() - start) * 1000)
uptime = time_formatter((time.time() - start_time) * 1000)
await x.edit(get_string("ping").format(end, uptime))
@@ -195,12 +210,15 @@ heroku_api = Var.HEROKU_API
fullsudo=True,
)
async def restartbt(ult):
- ok = await eor(ult, get_string("bot_5"))
+ ok = await ult.eor(get_string("bot_5"))
call_back()
if heroku_api:
return await restart(ok)
await bash("git pull && pip3 install -r requirements.txt")
- os.execl(sys.executable, sys.executable, "-m", "pyUltroid")
+ if len(sys.argv) > 1:
+ os.execl(sys.executable, sys.executable, "main.py")
+ else:
+ os.execl(sys.executable, sys.executable, "-m", "pyUltroid")
@ultroid_cmd(
@@ -217,52 +235,54 @@ async def shutdownbot(ult):
)
async def _(event):
opt = event.pattern_match.group(1)
+ file = f"ultroid{sys.argv[-1]}.log" if len(sys.argv) > 1 else "ultroid.log"
if opt == "heroku":
await heroku_logs(event)
elif opt == "carbon" and Carbon:
- event = await eor(event, get_string("com_1"))
- code = open("ultroid.log", "r").read()[-2500:]
+ event = await event.eor(get_string("com_1"))
+ code = open(file, "r").read()[-2500:]
file = await Carbon(
- base_url="https://carbonara.vercel.app/api/cook",
+ file_name="ultroid-logs",
code=code,
- background=choice(ATRA_COL),
- ).memorize("ultroid-logs")
+ backgroundColor=choice(ATRA_COL),
+ )
await event.reply("**Ultroid Logs.**", file=file)
+ elif opt == "open":
+ file = open("ultroid.log", "r").read()[-4000:]
+ return await event.eor(f"`{file}`")
else:
- await def_logs(event)
- await event.delete()
+ await def_logs(event, file)
+ await event.try_delete()
@in_pattern("alive", owner=True)
async def inline_alive(ult):
- pic = udB.get("ALIVE_PIC")
+ pic = udB.get_key("ALIVE_PIC")
uptime = time_formatter((time.time() - start_time) * 1000)
- header = udB.get("ALIVE_TEXT") or get_string("bot_1")
+ header = udB.get_key("ALIVE_TEXT") or get_string("bot_1")
y = Repo().active_branch
xx = Repo().remotes[0].config_reader.get("url")
rep = xx.replace(".git", f"/tree/{y}")
- kk = f" `[{y}]({rep})` "
- als = (get_string("alive_1")).format(
+ kk = f"{y}"
+ als = in_alive.format(
header,
- OWNER_NAME,
ultroid_version,
UltVer,
- uptime,
pyver(),
- __version__,
+ uptime,
kk,
)
- buttons = [
- [
- Button.url(get_string("bot_3"), "https://github.com/TeamUltroid/Ultroid"),
- Button.url(get_string("bot_4"), "t.me/UltroidSupport"),
- ]
- ]
+ if _e := udB.get_key("ALIVE_EMOJI"):
+ als = als.replace("🌀", _e)
builder = ult.builder
if pic:
try:
if ".jpg" in pic:
- results = [await builder.photo(pic, text=als, buttons=buttons)]
+ results = [
+ await builder.photo(
+ pic, text=als, parse_mode="html", buttons=buttons
+ )
+ ]
else:
_pic = resolve_bot_file_id(pic)
if _pic:
@@ -275,6 +295,7 @@ async def inline_alive(ult):
pic,
title="Inline Alive",
description="@TheUltroid",
+ parse_mode="html",
buttons=buttons,
)
]
@@ -282,6 +303,55 @@ async def inline_alive(ult):
except BaseException as er:
LOGS.info(er)
result = [
- await builder.article("Alive", text=als, link_preview=False, buttons=buttons)
+ await builder.article(
+ "Alive", text=als, parse_mode="html", link_preview=False, buttons=buttons
+ )
]
await ult.answer(result)
+
+
+@ultroid_cmd(pattern="update ?(.*)")
+async def _(e):
+ xx = await e.eor(get_string("upd_1"))
+ if e.pattern_match.group(1) and (
+ "fast" in e.pattern_match.group(1) or "soft" in e.pattern_match.group(1)
+ ):
+ await bash("git pull -f && pip3 install -r requirements.txt")
+ call_back()
+ await xx.edit(get_string("upd_7"))
+ os.execl(sys.executable, "python3", "-m", "pyUltroid")
+ return
+ m = await updater()
+ branch = (Repo.init()).active_branch
+ if m:
+ x = await asst.send_file(
+ udB.get_key("LOG_CHANNEL"),
+ ULTPIC,
+ caption="• **Update Available** •",
+ force_document=False,
+ buttons=Button.inline("Changelogs", data="changes"),
+ )
+ Link = x.message_link
+ await xx.edit(
+ f'[ChangeLogs]',
+ parse_mode="html",
+ link_preview=False,
+ )
+ else:
+ await xx.edit(
+ f'Your BOT is
up-to-date with
[{branch}]',
+ parse_mode="html",
+ link_preview=False,
+ )
+
+
+@callback("updtavail", owner=True)
+async def updava(event):
+ await event.delete()
+ await asst.send_file(
+ udB.get_key("LOG_CHANNEL"),
+ ULTPIC,
+ caption="• **Update Available** •",
+ force_document=False,
+ buttons=Button.inline("Changelogs", data="changes"),
+ )
diff --git a/plugins/broadcast.py b/plugins/broadcast.py
index 4de65baef880ae16dfa636a029753dfae34289b3..16d7bfa8c8141fbbc37c5bdcf40e5d7085424282 100644
--- a/plugins/broadcast.py
+++ b/plugins/broadcast.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -36,8 +36,7 @@ from . import HNDLR, LOGS, eor, get_string, udB, ultroid_bot, ultroid_cmd
)
async def broadcast_adder(event):
msgg = event.pattern_match.group(1)
- x = await eor(event, get_string("bd_1"))
- aldone = new = crsh = 0
+ x = await event.eor(get_string("bd_1"))
if msgg == "all":
await x.edit(get_string("bd_2"))
chats = [
@@ -45,6 +44,7 @@ async def broadcast_adder(event):
for e in await event.client.get_dialogs()
if (e.is_group or e.is_channel)
]
+ new = 0
for i in chats:
try:
if (
@@ -73,7 +73,7 @@ async def broadcast_adder(event):
await event.delete()
return
chat_id = event.chat_id
- if int(chat_id) == int(udB.get("LOG_CHANNEL")):
+ if int(chat_id) == int(udB.get_key("LOG_CHANNEL")):
return
if not is_channel_added(chat_id):
xx = add_channel(chat_id)
@@ -95,10 +95,10 @@ async def broadcast_adder(event):
)
async def broadcast_remover(event):
chat_id = event.pattern_match.group(1)
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
if chat_id == "all":
await x.edit(get_string("bd_8"))
- udB.delete("BROADCAST")
+ udB.del_key("BROADCAST")
await x.edit("Database cleared.")
return
if is_channel_added(chat_id):
@@ -121,7 +121,7 @@ async def broadcast_remover(event):
pattern="listchannels$",
)
async def list_all(event):
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
channels = get_channels()
num = get_no_channels()
if num == 0:
@@ -156,10 +156,10 @@ async def list_all(event):
)
async def forw(event):
if not event.is_reply:
- return await eor(event, get_string("ex_1"))
+ return await event.eor(get_string("ex_1"))
ultroid_bot = event.client
channels = get_channels()
- x = await eor(event, "Sending...")
+ x = await event.eor("Sending...")
if get_no_channels() == 0:
return await x.edit(f"Please add channels by using `{HNDLR}add` in them.")
error_count = 0
@@ -177,7 +177,7 @@ async def forw(event):
except Exception:
try:
await ultroid_bot.send_message(
- int(udB.get("LOG_CHANNEL")),
+ int(udB.get_key("LOG_CHANNEL")),
f"Error in sending at {channel}.",
)
except Exception as Em:
@@ -189,7 +189,7 @@ async def forw(event):
await x.edit(f"{sent_count} messages sent with {error_count} errors.")
if error_count > 0:
await ultroid_bot.send_message(
- int(udB.get("LOG_CHANNEL")), f"{error_count} Errors"
+ int(udB.get_key("LOG_CHANNEL")), f"{error_count} Errors"
)
@@ -198,7 +198,7 @@ async def forw(event):
allow_sudo=False,
)
async def sending(event):
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
if not event.is_reply:
return await x.edit(get_string("ex_1"))
channels = get_channels()
@@ -222,7 +222,7 @@ async def sending(event):
except Exception as error:
await ultroid_bot.send_message(
- int(udB.get("LOG_CHANNEL")),
+ int(udB.get_key("LOG_CHANNEL")),
f"Error in sending at {channel}.\n\n{error}",
)
error_count += 1
@@ -232,6 +232,6 @@ async def sending(event):
await x.edit(f"{sent_count} messages sent with {error_count} errors.")
if error_count > 0:
await ultroid_bot.send_message(
- int(udB.get("LOG_CHANNEL")),
+ int(udB.get_key("LOG_CHANNEL")),
f"{error_count} Errors",
)
diff --git a/plugins/button.py b/plugins/button.py
index 27650c709ff714e7f3d295839806a6164a6d0572..f711d9b724fb37add4fdfc68ba5332cd8f6e70d2 100644
--- a/plugins/button.py
+++ b/plugins/button.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -32,28 +32,28 @@ async def butt(event):
text = wt.text
if wt.media:
wut = mediainfo(wt.media)
- if wut.startswith(("pic", "gif")):
+ if wut and wut.startswith(("pic", "gif")):
dl = await wt.download_media()
variable = uf(dl)
media = "https://telegra.ph" + variable[0]
elif wut == "video":
if wt.media.document.size > 8 * 1000 * 1000:
- return await eor(event, get_string("com_4"), time=5)
+ return await event.eor(get_string("com_4"), time=5)
dl = await wt.download_media()
variable = uf(dl)
os.remove(dl)
media = "https://telegra.ph" + variable[0]
else:
- pack_bot_file_id(wt.media)
- if not text:
- text = event.text.split(maxsplit=1)
- if len(text) <= 1:
- return await eor(
- event,
+ media = pack_bot_file_id(wt.media)
+ try:
+ text = event.text.split(maxsplit=1)[1]
+ except IndexError:
+ if not text:
+ return await event.eor(
f"**Please give some text in correct format.**\n\n`{HNDLR}help button`",
)
- text = text[1]
text, buttons = get_msg_button(text)
if buttons:
buttons = create_tl_btn(buttons)
- return await something(event, text, None, buttons)
+ await something(event, text, media, buttons)
+ await event.delete()
diff --git a/plugins/calculator.py b/plugins/calculator.py
index fa86844aa1db31c336715323871860c0acc43434..e10add86cbea9eef89d4add77d9f47225b9a5419 100644
--- a/plugins/calculator.py
+++ b/plugins/calculator.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -45,7 +45,7 @@ lst.append([Button.inline("=", data="calc=")])
@ultroid_cmd(pattern="calc")
async def icalc(e):
- udB.delete("calc")
+ udB.del_key("calc")
if e.client._bot:
return await e.reply(get_string("calc_1"), buttons=lst)
results = await e.client.inline_query(asst.me.username, "calc")
diff --git a/plugins/carbon.py b/plugins/carbon.py
index 0441e8d31f937873511812da56a1ddbc03866a38..efc2ea9f035166c1af4725c9752d19eb4d2f3d1c 100644
--- a/plugins/carbon.py
+++ b/plugins/carbon.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -18,9 +18,7 @@
"""
import random
-from carbonnow import Carbon
-
-from . import eor, get_string, inline_mention, os, ultroid_cmd
+from . import Carbon, eor, get_string, inline_mention, os, ultroid_cmd
all_col = [
"Black",
@@ -178,9 +176,9 @@ all_col = [
pattern="(rc|c)arbon",
)
async def crbn(event):
- xxxx = await eor(event, get_string("com_1"))
+ xxxx = await event.eor(get_string("com_1"))
te = event.text
- col = random.choice(all_col) if te[1] == "r" else None
+ col = random.choice(all_col) if te[1] == "r" else "White"
if event.reply_to_msg_id:
temp = await event.get_reply_message()
if temp.media:
@@ -195,10 +193,7 @@ async def crbn(event):
code = event.text.split(" ", maxsplit=1)[1]
except IndexError:
return await eor(xxxx, get_string("carbon_2"))
- carbon = Carbon(
- base_url="https://carbonara.vercel.app/api/cook", code=code, background=col
- )
- xx = await carbon.memorize("ultroid_carbon")
+ xx = await Carbon(code=code, file_name="ultroid_carbon", backgroundColor=col)
await xxxx.delete()
await event.reply(
f"Carbonised by {inline_mention(event.sender)}",
@@ -212,8 +207,8 @@ async def crbn(event):
async def crbn(event):
match = event.pattern_match.group(1)
if not match:
- return await eor(event, get_string("carbon_3"))
- msg = await eor(event, get_string("com_1"))
+ return await event.eor(get_string("carbon_3"))
+ msg = await event.eor(get_string("com_1"))
if event.reply_to_msg_id:
temp = await event.get_reply_message()
if temp.media:
@@ -230,13 +225,7 @@ async def crbn(event):
match = match[0]
except IndexError:
return await eor(msg, get_string("carbon_2"))
- carbon = Carbon(
- base_url="https://carbonara.vercel.app/api/cook", code=code, background=match
- )
- try:
- xx = await carbon.memorize("ultroid_carbon")
- except Exception as er:
- return await msg.edit(str(er))
+ xx = await Carbon(code=code, backgroundColor=match)
await msg.delete()
await event.reply(
f"Carbonised by {inline_mention(event.sender)}",
diff --git a/plugins/channelhacks.py b/plugins/channelhacks.py
index aba4f6209ada5a1915fdce1f638adbc5795233e6..9115d6440e10a2cfad6d629f6ba6451e62ef5730 100644
--- a/plugins/channelhacks.py
+++ b/plugins/channelhacks.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -32,7 +32,7 @@
Show List of Ur channels
'you can set many channels in database'
- 'For activating auto-post use `{i}setredis AUTOPOST True` '
+ 'For activating auto-post use `{i}setdb AUTOPOST True` '
"""
import asyncio
@@ -56,7 +56,7 @@ from . import asst, eor, events, get_string, udB, ultroid_bot, ultroid_cmd
@ultroid_bot.on(events.NewMessage())
async def _(e):
- if udB.get("AUTOPOST") != "True":
+ if udB.get_key("AUTOPOST") != "True":
return
x = get_source_channels()
th = await e.get_chat()
@@ -67,13 +67,13 @@ async def _(e):
try:
await ultroid_bot.send_message(int(ys), e.message)
except Exception as ex:
- await asst.send_message(int(udB["LOG_CHANNEL"]), str(ex))
+ await asst.send_message(int(udB.get_key("LOG_CHANNEL")), str(ex))
@ultroid_cmd(pattern="shift (.*)")
async def _(e):
x = e.pattern_match.group(1)
- z = await eor(e, get_string("com_1"))
+ z = await e.eor(get_string("com_1"))
a, b = x.split("|")
try:
c = int(a)
@@ -113,18 +113,18 @@ async def source(e):
return
if not is_source_channel_added(y):
add_source_channel(y)
- await eor(e, get_string("cha_2"))
+ await e.eor(get_string("cha_2"))
elif is_source_channel_added(y):
- await eor(e, get_string("cha_3"))
+ await e.eor(get_string("cha_3"))
@ultroid_cmd(pattern="dsource ?(.*)")
async def dd(event):
chat_id = event.pattern_match.group(1)
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
if chat_id == "all":
await x.edit(get_string("bd_8"))
- udB.delete("CH_SOURCE")
+ udB.del_key("CH_SOURCE")
await x.edit(get_string("cha_4"))
return
try:
@@ -147,7 +147,7 @@ async def dd(event):
@ultroid_cmd(pattern="listsource")
async def list_all(event):
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
channels = get_source_channels()
num = get_no_source_channels()
if num == 0:
@@ -191,18 +191,18 @@ async def destination(e):
return
if not is_destination_added(y):
add_destination(y)
- await eor(e, "Destination added succesfully")
+ await e.eor("Destination added succesfully")
elif is_destination_added(y):
- await eor(e, "Destination channel already added")
+ await e.eor("Destination channel already added")
@ultroid_cmd(pattern="ddest ?(.*)")
async def dd(event):
chat_id = event.pattern_match.group(1)
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
if chat_id == "all":
await x.edit(get_string("bd_8"))
- udB.delete("CH_DESTINATION")
+ udB.del_key("CH_DESTINATION")
await x.edit("Destinations database cleared.")
return
try:
@@ -226,7 +226,7 @@ async def dd(event):
@ultroid_cmd(pattern="listdest")
async def list_all(event):
ultroid_bot = event.client
- x = await eor(event, get_string("com_1"))
+ x = await event.eor(get_string("com_1"))
channels = get_destinations()
num = get_no_destinations()
if not num:
diff --git a/plugins/chat_bot.py b/plugins/chatbot.py
similarity index 65%
rename from plugins/chat_bot.py
rename to plugins/chatbot.py
index 7c3dfd6997418248c689013d38ff2ac8932c5e0e..bc45425eb75da874a1e9e7859afc1f8a8a64a98a 100644
--- a/plugins/chat_bot.py
+++ b/plugins/chatbot.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2020 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -20,10 +20,9 @@
List the currently AI added users.
"""
-from pyUltroid.dB.chatBot_db import add_chatbot, get_all_added, rem_chatbot
from pyUltroid.functions.tools import get_chatbot_reply
-from . import eod, eor, get_string, inline_mention, ultroid_cmd
+from . import eod, get_string, inline_mention, udB, ultroid_cmd
@ultroid_cmd(pattern="repai")
@@ -36,7 +35,7 @@ async def im_lonely_chat_with_me(event):
except IndexError:
return await eod(event, get_string("tban_1"), time=10)
reply_ = await get_chatbot_reply(message=message)
- await eor(event, reply_)
+ await event.eor(reply_)
@ultroid_cmd(pattern="addai")
@@ -51,9 +50,10 @@ async def rem_chatBot(event):
@ultroid_cmd(pattern="listai")
async def lister(event):
- users = get_all_added(event.chat_id)
+ key = udB.get_key("CHATBOT_USERS") or {}
+ users = key.get(event.chat_id, [])
if not users:
- return await eor(event, get_string("chab_2"), time=5)
+ return await event.eor(get_string("chab_2"), time=5)
msg = "**Total List Of AI Enabled Users In This Chat :**\n\n"
for i in users:
try:
@@ -62,32 +62,38 @@ async def lister(event):
except BaseException:
user = f"`{i}`"
msg += "• {}\n".format(user)
- await eor(event, msg, link_preview=False)
+ await event.eor(msg, link_preview=False)
async def chat_bot_fn(event, type_):
if event.reply_to:
- re_ = await event.get_reply_message()
- user = await re_.get_sender()
- user_id = re_.sender_id
+ user_ = (await event.get_reply_message()).sender
else:
temp = event.text.split(maxsplit=1)
try:
- user = await event.client.get_entity(temp[1])
- user_id = user.id
+ user_ = await event.client.get_entity(temp[1])
except BaseException:
if event.is_private:
- user_id = event.chat_id
- user = await event.get_chat()
+ user_ = event.chat
else:
return await eod(
event,
get_string("chab_1"),
)
+ key = udB.get_key("CHATBOT_USERS") or {}
+ chat = event.chat_id
+ user = user_.id
if type_ == "add":
- add_chatbot(event.chat_id, user_id)
- if type_ == "remov":
- rem_chatbot(event.chat_id, user_id)
- await eor(
- event, f"**ChatBot:**\n{type_}ed {inline_mention(user)}"
- )
+ if key.get(chat):
+ if user not in key[chat]:
+ key[chat].append(user)
+ else:
+ key.update({chat: [user]})
+ elif type_ == "remov":
+ if key.get(chat):
+ if user in key[chat]:
+ key[chat].remove(user)
+ if chat in key and not key[chat]:
+ del key[chat]
+ udB.set_key("CHATBOT_USERS", str(key))
+ await event.eor(f"**ChatBot:**\n{type_}ed {inline_mention(user_)}")
diff --git a/plugins/chats.py b/plugins/chats.py
index e458d1441d519ae80fe795ae47502f8907098d67..4d50cb48c2d93487b7d59222f8efe764ffd558b6 100644
--- a/plugins/chats.py
+++ b/plugins/chats.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -42,12 +42,12 @@ from telethon.tl.functions.channels import (
)
from telethon.tl.functions.messages import (
CreateChatRequest,
- DeleteChatUserRequest,
ExportChatInviteRequest,
GetFullChatRequest,
)
from telethon.tl.types import (
ChannelParticipantsKicked,
+ User,
UserStatusEmpty,
UserStatusLastMonth,
UserStatusLastWeek,
@@ -56,17 +56,7 @@ from telethon.tl.types import (
UserStatusRecently,
)
-from . import (
- HNDLR,
- eor,
- get_string,
- get_user_id,
- mediainfo,
- os,
- types,
- udB,
- ultroid_cmd,
-)
+from . import HNDLR, LOGS, asst, get_string, mediainfo, os, types, udB, ultroid_cmd
@ultroid_cmd(
@@ -74,32 +64,36 @@ from . import (
groups_only=True,
)
async def _(e):
- xx = await eor(e, get_string("com_1"))
+ xx = await e.eor(get_string("com_1"))
try:
match = e.text.split(" ", maxsplit=1)[1]
- chat = "-100" + str(await get_user_id(match))
+ chat = await e.client.parse_id(match)
except IndexError:
chat = e.chat_id
try:
await e.client(DeleteChannelRequest(chat))
except TypeError:
- return await eor(xx, get_string("chats_1"), time=10)
+ return await xx.eor(get_string("chats_1"), time=10)
except no_admin:
- return await eor(xx, get_string("chats_2"), time=10)
+ return await xx.eor(get_string("chats_2"), time=10)
await e.client.send_message(
- int(udB.get("LOG_CHANNEL")), get_string("chats_6").format(e.chat_id)
+ int(udB.get_key("LOG_CHANNEL")), get_string("chats_6").format(e.chat_id)
)
@ultroid_cmd(
pattern="getlink$",
groups_only=True,
- type=["official", "manager"],
+ manager=True,
)
async def _(e):
- chat = await e.get_chat()
- if chat.username:
- return await eor(e, f"Username: @{chat.username}")
+ reply = await e.get_reply_message()
+ if reply and not isinstance(reply.sender, User):
+ chat = await reply.get_sender()
+ else:
+ chat = await e.get_chat()
+ if hasattr(chat, "username") and chat.username:
+ return await e.eor(f"Username: @{chat.username}")
if isinstance(chat, types.Chat):
FC = await e.client(GetFullChatRequest(chat.id))
elif isinstance(chat, types.Channel):
@@ -113,9 +107,9 @@ async def _(e):
ExportChatInviteRequest(e.chat_id),
)
except no_admin:
- return await eor(e, get_string("chats_2"), time=10)
+ return await e.eor(get_string("chats_2"), time=10)
link = r.link
- await eor(e, f"Link:- {link}")
+ await e.eor(f"Link:- {link}")
@ultroid_cmd(
@@ -129,22 +123,16 @@ async def _(e):
group_ = group_name.split(" ; ", maxsplit=1)
group_name = group_[0]
username = group_[1]
- xx = await eor(e, get_string("com_1"))
+ xx = await e.eor(get_string("com_1"))
if type_of_group == "b":
try:
r = await e.client(
CreateChatRequest(
- users=["@missrose_bot"],
+ users=[asst.me.username],
title=group_name,
),
)
created_chat_id = r.chats[0].id
- await e.client(
- DeleteChatUserRequest(
- chat_id=created_chat_id,
- user_id="@missrose_bot",
- ),
- )
result = await e.client(
ExportChatInviteRequest(
peer=created_chat_id,
@@ -190,44 +178,38 @@ async def _(e):
@ultroid_cmd(
- pattern="setgpic ?(.*)",
- groups_only=True,
- admins_only=True,
- type=["official", "manager"],
+ pattern="setgpic ?(.*)", admins_only=True, manager=True, require="change_info"
)
async def _(ult):
if not ult.is_reply:
- return await eor(ult, "`Reply to a Media..`", time=5)
+ return await ult.eor("`Reply to a Media..`", time=5)
match = ult.pattern_match.group(1)
if not ult.client._bot and match:
try:
- chat = await get_user_id(match)
+ chat = await ult.client.parse_id(match)
except Exception as ok:
- return await eor(ult, str(ok))
+ return await ult.eor(str(ok))
else:
chat = ult.chat_id
reply_message = await ult.get_reply_message()
if reply_message.media:
replfile = await reply_message.download_media()
else:
- return await eor(ult, "Reply to a Photo or Video..")
+ return await ult.eor("Reply to a Photo or Video..")
file = await ult.client.upload_file(replfile)
mediain = mediainfo(reply_message.media)
try:
if "pic" not in mediain:
file = types.InputChatUploadedPhoto(video=file)
await ult.client(EditPhotoRequest(chat, file))
- await eor(ult, "`Group Photo has Successfully Changed !`", time=5)
+ await ult.eor("`Group Photo has Successfully Changed !`", time=5)
except Exception as ex:
- await eor(ult, "Error occured.\n`{}`".format(str(ex)), time=5)
+ await ult.eor("Error occured.\n`{}`".format(str(ex)), time=5)
os.remove(replfile)
@ultroid_cmd(
- pattern="delgpic ?(.*)",
- groups_only=True,
- admins_only=True,
- type=["official", "manager"],
+ pattern="delgpic ?(.*)", admins_only=True, manager=True, require="change_info"
)
async def _(ult):
match = ult.pattern_match.group(1)
@@ -239,15 +221,12 @@ async def _(ult):
text = "`Removed Chat Photo..`"
except Exception as E:
text = str(E)
- return await eor(ult, text, time=5)
+ return await ult.eor(text, time=5)
-@ultroid_cmd(
- pattern="unbanall$",
- groups_only=True,
-)
+@ultroid_cmd(pattern="unbanall$", manager=True, admins_only=True, require="ban_users")
async def _(event):
- xx = await eor(event, "Searching Participant Lists.")
+ xx = await event.eor("Searching Participant Lists.")
p = 0
title = (await event.get_chat()).title
async for i in event.client.iter_participants(
@@ -258,9 +237,11 @@ async def _(event):
try:
await event.client.edit_permissions(event.chat_id, i, view_messages=True)
p += 1
- except BaseException:
+ except no_admin:
pass
- await eor(xx, f"{title}: {p} unbanned", time=5)
+ except BaseException as er:
+ LOGS.exception(er)
+ await xx.eor(f"{title}: {p} unbanned", time=5)
@ultroid_cmd(
@@ -270,7 +251,7 @@ async def _(event):
fullsudo=True,
)
async def _(event):
- xx = await eor(event, get_string("com_1"))
+ xx = await event.eor(get_string("com_1"))
input_str = event.pattern_match.group(1)
p, a, b, c, d, m, n, y, w, o, q, r = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
async for i in event.client.iter_participants(event.chat_id):
@@ -369,4 +350,4 @@ async def _(event):
required_string += f" `{HNDLR}rmusers recently` **••** `{r}`\n"
required_string += f" `{HNDLR}rmusers bot` **••** `{b}`\n"
required_string += f" `{HNDLR}rmusers none` **••** `{n}`"
- await eor(xx, required_string)
+ await xx.eor(required_string)
diff --git a/plugins/clean_action.py b/plugins/cleanaction.py
similarity index 51%
rename from plugins/clean_action.py
rename to plugins/cleanaction.py
index e582f7887b29792ec7d7a858e17dcc43ca5d551e..78d4a81ae0982be9b65f222b072a890e9619b168 100644
--- a/plugins/clean_action.py
+++ b/plugins/cleanaction.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -18,35 +18,41 @@
"""
-from pyUltroid.dB.clean_db import add_clean, rem_clean
+from telethon.utils import get_display_name
-from . import eor, get_string, udB, ultroid_cmd
+from . import get_string, udB, ultroid_cmd
@ultroid_cmd(pattern="addclean$", admins_only=True)
async def _(e):
- add_clean(e.chat_id)
- await eor(e, get_string("clan_1"), time=5)
+ key = udB.get_key("CLEANCHAT") or []
+ if e.chat_id in key:
+ return await eod(e, get_string("clan_5"))
+ key.append(e.chat_id)
+ udB.set_key("CLEANCHAT", key)
+ await e.eor(get_string("clan_1"), time=5)
@ultroid_cmd(pattern="remclean$")
async def _(e):
- rem_clean(e.chat_id)
- await eor(e, get_string("clan_2"), time=5)
+ key = udB.get_key("CLEANCHAT") or []
+ if e.chat_id in key:
+ key.remove(e.chat_id)
+ udB.set_key("CLEANCHAT", key)
+ await e.eor(get_string("clan_2"), time=5)
@ultroid_cmd(pattern="listclean$")
async def _(e):
- k = udB.get("CLEANCHAT")
+ k = udB.get_key("CLEANCHAT")
if k:
- k = k.split(" ")
o = ""
for x in k:
try:
- title = e.chat.title
+ title = get_display_name(await e.client.get_entity(x))
except BaseException:
title = get_string("clan_3")
- o += x + " " + title + "\n"
- await eor(e, o)
+ o += f"{x} {title}\n"
+ await e.eor(o)
else:
- await eor(e, get_string("clan_4"), time=5)
+ await e.eor(get_string("clan_4"), time=5)
diff --git a/plugins/compressor.py b/plugins/compressor.py
index 85a3babd5732e12f9340491075e6532360c66878..f8fd6dfb5e213566941140d75c629c3ea181bfa1 100644
--- a/plugins/compressor.py
+++ b/plugins/compressor.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -31,7 +31,6 @@ from telethon.tl.types import DocumentAttributeVideo
from . import (
bash,
downloader,
- eor,
get_string,
humanbytes,
math,
@@ -64,7 +63,7 @@ async def _(e):
name = ""
if not name:
name = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"
- xxx = await eor(e, get_string("audiotools_5"))
+ xxx = await e.eor(get_string("audiotools_5"))
c_time = time.time()
file = await downloader(
"resources/downloads/" + name,
@@ -182,4 +181,4 @@ async def _(e):
os.remove(out)
os.remove(progress)
else:
- await eor(e, get_string("audiotools_8"), time=5)
+ await e.eor(get_string("audiotools_8"), time=5)
diff --git a/plugins/converter.py b/plugins/converter.py
index 499161e5bb261a453d28f5d6ccca289ef3812a9d..6f3057da083c57beeb07ec7553ce12cd6680a1ae 100644
--- a/plugins/converter.py
+++ b/plugins/converter.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -28,15 +28,22 @@
import os
import time
+from . import LOGS
+
try:
import cv2
except ImportError:
cv2 = None
-from PIL import Image
+try:
+ from PIL import Image
+except ImportError:
+ LOGS.info(f"{__file__}: PIL not Installed.")
+ Image = None
+
from telegraph import upload_file as uf
-from . import bash, downloader, eor, get_paste, get_string, udB, ultroid_cmd, uploader
+from . import bash, downloader, get_paste, get_string, udB, ultroid_cmd, uploader
opn = []
@@ -51,13 +58,13 @@ async def _(e):
elif r.document and r.document.thumbs:
dl = await r.download_media(thumb=-1)
else:
- return await eor(e, "`Reply to Photo or media with thumb...`")
+ return await e.eor("`Reply to Photo or media with thumb...`")
variable = uf(dl)
os.remove(dl)
nn = "https://telegra.ph" + variable[0]
- udB.set("CUSTOM_THUMBNAIL", str(nn))
+ udB.set_key("CUSTOM_THUMBNAIL", str(nn))
await bash(f"wget {nn} -O resources/extras/ultroid.jpg")
- await eor(e, get_string("cvt_6").format(nn), link_preview=False)
+ await e.eor(get_string("cvt_6").format(nn), link_preview=False)
@ultroid_cmd(
@@ -67,11 +74,11 @@ async def imak(event):
reply = await event.get_reply_message()
t = time.time()
if not reply:
- return await eor(event, get_string("cvt_1"))
+ return await event.eor(get_string("cvt_1"))
inp = event.pattern_match.group(1)
if not inp:
- return await eor(event, get_string("cvt_2"))
- xx = await eor(event, get_string("com_1"))
+ return await event.eor(get_string("cvt_2"))
+ xx = await event.eor(get_string("com_1"))
if reply.media:
if hasattr(reply.media, "document"):
file = reply.media.document
@@ -86,7 +93,11 @@ async def imak(event):
file = image.name
else:
file = await event.client.download_media(reply.media)
- os.rename(file, inp)
+ if os.path.exists(inp):
+ os.remove(inp)
+ await bash(f"""ffmpeg -i "{file}" "{inp}" -y""")
+ if not os.path.exists(inp) or os.path.exists(inp) and not os.path.getsize(inp):
+ os.rename(file, inp)
k = time.time()
xxx = await uploader(inp, inp, k, xx, get_string("com_6"))
await event.reply(
@@ -105,9 +116,9 @@ async def imak(event):
async def imak(event):
reply = await event.get_reply_message()
if not (reply and (reply.media)):
- await eor(event, get_string("cvt_3"))
+ await event.eor(get_string("cvt_3"))
return
- xx = await eor(event, get_string("com_1"))
+ xx = await event.eor(get_string("com_1"))
image = await reply.download_media()
file = "ult.png"
if image.endswith((".webp", ".png")):
@@ -131,9 +142,9 @@ async def imak(event):
async def smak(event):
reply = await event.get_reply_message()
if not (reply and (reply.media)):
- await eor(event, get_string("cvt_3"))
+ await event.eor(get_string("cvt_3"))
return
- xx = await eor(event, get_string("com_1"))
+ xx = await event.eor(get_string("com_1"))
image = await reply.download_media()
file = "ult.webp"
if image.endswith((".webp", ".png", ".jpg")):
@@ -155,8 +166,8 @@ async def smak(event):
async def _(event):
input_str = event.pattern_match.group(1)
if not (input_str and event.is_reply):
- return await eor(event, get_string("cvt_1"), time=5)
- xx = await eor(event, get_string("com_1"))
+ return await event.eor(get_string("cvt_1"), time=5)
+ xx = await event.eor(get_string("com_1"))
a = await event.get_reply_message()
if not a.message:
return await xx.edit(get_string("ex_1"))
@@ -169,19 +180,23 @@ async def _(event):
@ultroid_cmd(
- pattern="open$",
+ pattern="open ?(.*)",
)
async def _(event):
a = await event.get_reply_message()
- if not (a and a.media):
- return await eor(event, get_string("cvt_7"), time=5)
- xx = await eor(event, get_string("com_1"))
- b = await a.download_media()
+ b = event.pattern_match.group(1)
+ if not ((a and a.media) or (b and os.path.exists(b))):
+ return await event.eor(get_string("cvt_7"), time=5)
+ xx = await event.eor(get_string("com_1"))
+ rem = None
+ if not b:
+ b = await a.download_media()
+ rem = True
try:
with open(b) as c:
d = c.read()
except UnicodeDecodeError:
- return await eor(xx, get_string("cvt_8"), time=5)
+ return await xx.eor(get_string("cvt_8"), time=5)
try:
await xx.edit(f"```{d}```")
except BaseException:
@@ -189,4 +204,5 @@ async def _(event):
await xx.edit(
f"**MESSAGE EXCEEDS TELEGRAM LIMITS**\n\nSo Pasted It On [SPACEBIN](https://spaceb.in/{key})"
)
- os.remove(b)
+ if rem:
+ os.remove(b)
diff --git a/plugins/core.py b/plugins/core.py
index 7ad76b42a32c8a9dd5f1b9c11fee1390de21250d..d8037a64da82ab27931803142dad16122e8506bd 100644
--- a/plugins/core.py
+++ b/plugins/core.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -32,7 +32,7 @@ import os
from pyUltroid.startup.loader import load_addons
-from . import eod, eor, get_string, requests, safeinstall, ultroid_cmd, un_plug
+from . import eod, get_string, requests, safeinstall, ultroid_cmd, un_plug
@ultroid_cmd(pattern="install", fullsudo=True)
@@ -46,7 +46,7 @@ async def install(event):
async def unload(event):
shortname = event.pattern_match.group(1)
if not shortname:
- await eor(event, get_string("core_9"))
+ await event.eor(get_string("core_9"))
return
lsd = os.listdir("addons")
lst = os.listdir("plugins")
@@ -54,13 +54,13 @@ async def unload(event):
if zym in lsd:
try:
un_plug(shortname)
- await eor(event, f"**Uɴʟᴏᴀᴅᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3)
+ await event.eor(f"**Uɴʟᴏᴀᴅᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3)
except Exception as ex:
- return await eor(event, str(ex))
+ return await event.eor(str(ex))
elif zym in lst:
- return await eor(event, get_string("core_11"), time=3)
+ return await event.eor(get_string("core_11"), time=3)
else:
- return await eor(event, f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
+ return await event.eor(f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
@ultroid_cmd(
@@ -69,7 +69,7 @@ async def unload(event):
async def uninstall(event):
shortname = event.pattern_match.group(1)
if not shortname:
- await eor(event, get_string("core_13"))
+ await event.eor(get_string("core_13"))
return
lsd = os.listdir("addons")
lst = os.listdir("plugins")
@@ -77,14 +77,14 @@ async def uninstall(event):
if zym in lsd:
try:
un_plug(shortname)
- await eor(event, f"**Uɴɪɴsᴛᴀʟʟᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3)
+ await event.eor(f"**Uɴɪɴsᴛᴀʟʟᴇᴅ** `{shortname}` **Sᴜᴄᴄᴇssғᴜʟʟʏ.**", time=3)
os.remove(f"addons/{shortname}.py")
except Exception as ex:
- return await eor(event, str(ex))
+ return await event.eor(str(ex))
elif zym in lst:
- return await eor(event, get_string("core_15"), time=3)
+ return await event.eor(get_string("core_15"), time=3)
else:
- return await eor(event, f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
+ return await event.eor(f"**Nᴏ Pʟᴜɢɪɴ Nᴀᴍᴇᴅ** `{shortname}`", time=3)
@ultroid_cmd(
@@ -94,7 +94,7 @@ async def uninstall(event):
async def load(event):
shortname = event.pattern_match.group(1)
if not shortname:
- await eor(event, get_string("core_16"))
+ await event.eor(get_string("core_16"))
return
try:
try:
@@ -102,7 +102,7 @@ async def load(event):
except BaseException:
pass
load_addons(shortname)
- await eor(event, get_string("core_17").format(shortname), time=3)
+ await event.eor(get_string("core_17").format(shortname), time=3)
except Exception as e:
await eod(
event,
@@ -114,13 +114,13 @@ async def load(event):
@ultroid_cmd(pattern="getaddons ?(.*)", fullsudo=True)
async def get_the_addons_lol(event):
thelink = event.pattern_match.group(1)
- xx = await eor(event, get_string("com_1"))
+ xx = await event.eor(get_string("com_1"))
fool = get_string("gas_1")
if thelink is None:
- return await eor(xx, fool, time=10)
+ return await xx.eor(fool, time=10)
split_thelink = thelink.split("/")
if "raw" not in thelink:
- return await eor(xx, fool, time=10)
+ return await xx.eor(fool, time=10)
name_of_it = split_thelink[(len(split_thelink) - 1)]
plug = requests.get(thelink).text
fil = f"addons/{name_of_it}"
@@ -131,7 +131,7 @@ async def get_the_addons_lol(event):
shortname = name_of_it.split(".")[0]
try:
load_addons(shortname)
- await eor(xx, get_string("core_17").format(shortname), time=15)
+ await xx.eor(get_string("core_17").format(shortname), time=15)
except Exception as e:
await eod(
xx,
diff --git a/plugins/database.py b/plugins/database.py
new file mode 100644
index 0000000000000000000000000000000000000000..912cda51de04c64173a43f051bff951d881c48ce
--- /dev/null
+++ b/plugins/database.py
@@ -0,0 +1,93 @@
+# Ultroid - UserBot
+# Copyright (C) 2021-2022 TeamUltroid
+#
+# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
+# PLease read the GNU Affero General Public License in
+# .
+"""
+✘ Commands Available -
+
+• **DataBase Commands, do not use if you don't know what it is.**
+
+• `{i}setdb key | value`
+ Set Value in Database.
+ e.g :
+ `{i}setdb hi there`
+ `{i}setdb hi there | ultroid here`
+
+• `{i}deldb key`
+ Delete Key from DB.
+
+• `{i}rendb old keyname | new keyname`
+ Update Key Name
+"""
+
+import re
+
+from . import Redis, eor, get_string, udB, ultroid_cmd
+
+
+@ultroid_cmd(pattern="setdb ?(.*)", fullsudo=True)
+async def _(ult):
+ match = ult.pattern_match.group(1)
+ if not match:
+ return await ult.eor("Provide key and value to set!")
+ try:
+ delim = " " if re.search("[|]", match) is None else " | "
+ data = match.split(delim, maxsplit=1)
+ if data[0] in ["--extend", "-e"]:
+ data = data[1].split(maxsplit=1)
+ data[1] = str(udB.get_key(data[0])) + " " + data[1]
+ udB.set_key(data[0], data[1])
+ redisdata = Redis(data[0])
+ await ult.eor(
+ "**DB Key Value Pair Updated\nKey :** `{}`\n**Value :** `{}`".format(
+ data[0],
+ redisdata,
+ ),
+ )
+ except BaseException:
+ await ult.eor(get_string("com_7"))
+
+
+@ultroid_cmd(pattern="deldb ?(.*)", fullsudo=True)
+async def _(ult):
+ key = ult.pattern_match.group(1)
+ if not key:
+ return await ult.eor("Give me a key name to delete!", time=5)
+ _ = key.split(maxsplit=1)
+ try:
+ if _[0] == "-m":
+ for key in _[1].split():
+ k = udB.del_key(key)
+ key = _[1]
+ else:
+ k = udB.del_key(key)
+ if k == 0:
+ return await ult.eor("`No Such Key.`")
+ await ult.eor(f"`Successfully deleted key {key}`")
+ except BaseException:
+ await ult.eor(get_string("com_7"))
+
+
+@ultroid_cmd(pattern="rendb ?(.*)", fullsudo=True)
+async def _(ult):
+ match = ult.pattern_match.group(1)
+ if not match:
+ return await ult.eor("`Provide Keys name to rename..`")
+ delim = " " if re.search("[|]", match) is None else " | "
+ data = match.split(delim)
+ if Redis(data[0]):
+ try:
+ udB.rename(data[0], data[1])
+ await eor(
+ ult,
+ "**DB Key Rename Successful\nOld Key :** `{}`\n**New Key :** `{}`".format(
+ data[0],
+ data[1],
+ ),
+ )
+ except BaseException:
+ await ult.eor(get_string("com_7"))
+ else:
+ await ult.eor("Key not found")
diff --git a/plugins/devtools.py b/plugins/devtools.py
index dcb677309695525f304790146453a7613ab6dc73..40781e5182c8b7da871dabb14246f0a36202b787 100644
--- a/plugins/devtools.py
+++ b/plugins/devtools.py
@@ -1,9 +1,10 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# .
+
"""
✘ Commands Available -
@@ -25,16 +26,20 @@
• `{i}sysinfo`
Shows System Info.
"""
-import io
+
import sys
import traceback
+from io import BytesIO, StringIO
from os import remove
from pprint import pprint
+from telethon.utils import get_display_name
+
+# Used for Formatting Eval Code, if installed
try:
- from carbonnow import Carbon
+ import black
except ImportError:
- Carbon = None
+ black = None
from . import *
@@ -43,12 +48,11 @@ from . import *
pattern="sysinfo$",
)
async def _(e):
- xx = await eor(e, get_string("com_1"))
+ xx = await e.eor(get_string("com_1"))
x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")
with open("neo.txt", "r") as neo:
p = (neo.read()).replace("\n\n", "")
- ok = Carbon(base_url="https://carbonara.vercel.app/api/cook", code=p)
- haa = await ok.memorize("neofetch")
+ haa = await Carbon(code=p, file_name="neofetch")
await e.reply(file=haa)
await xx.delete()
remove("neo.txt")
@@ -56,14 +60,12 @@ async def _(e):
@ultroid_cmd(pattern="bash", fullsudo=True, only_devs=True)
async def _(event):
- xx = await eor(event, get_string("com_1"))
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
- return await eor(xx, get_string("devs_1"), time=10)
- reply_to_id = event.message.id
- if event.reply_to_msg_id:
- reply_to_id = event.reply_to_msg_id
+ return await event.eor(get_string("devs_1"), time=10)
+ xx = await event.eor(get_string("com_1"))
+ reply_to_id = event.reply_to_msg_id or event.id
stdout, stderr = await bash(cmd)
OUT = f"**☞ BASH\n\n• COMMAND:**\n`{cmd}` \n\n"
if stderr:
@@ -76,7 +78,7 @@ async def _(event):
OUT += "**• OUTPUT:**\n`Success`"
if len(OUT) > 4096:
ultd = OUT.replace("`", "").replace("**", "").replace("__", "")
- with io.BytesIO(str.encode(ultd)) as out_file:
+ with BytesIO(str.encode(ultd)) as out_file:
out_file.name = "bash.txt"
await event.client.send_file(
event.chat_id,
@@ -93,44 +95,100 @@ async def _(event):
await xx.edit(OUT)
-p, pp = print, pprint # ignore: pylint
+pp = pprint # ignore: pylint
bot = ultroid = ultroid_bot
+_ignore_eval = []
+
+
+def _parse_eval(value):
+ if value is None:
+ return
+ if hasattr(value, "stringify"):
+ try:
+ return value.stringify()
+ except TypeError:
+ pass
+ elif isinstance(value, dict):
+ try:
+ return json_parser(value, indent=1)
+ except BaseException:
+ pass
+ # is to_dict is also Good option to format?
+ return str(value)
+
@ultroid_cmd(pattern="eval", fullsudo=True, only_devs=True)
async def _(event):
- if len(event.text) > 5 and event.text[5] != " ":
- return
- xx = await eor(event, get_string("com_1"))
try:
cmd = event.text.split(" ", maxsplit=1)[1]
except IndexError:
- return await eor(xx, get_string("devs_2"), time=5)
- if event.reply_to_msg_id:
- reply_to_id = event.reply_to_msg_id
+ return await event.eor(get_string("devs_2"), time=5)
+ silent = False
+ if cmd.split()[0] in ["-s", "--silent"]:
+ try:
+ cmd = cmd.split(maxsplit=1)[1]
+ except IndexError:
+ return await event.eor("->> Wrong Format <<-")
+ await event.delete()
+ silent = True
+ elif cmd.split()[0] in ["-n", "-noedit"]:
+ try:
+ cmd = cmd.split(maxsplit=1)[1]
+ except IndexError:
+ return await event.eor("->> Wrong Format <<-")
+ xx = await event.reply(get_string("com_1"))
+ else:
+ xx = await event.eor(get_string("com_1"))
+ if black:
+ try:
+ cmd = black.format_str(cmd, mode=black.Mode())
+ except BaseException:
+ # Consider it as Code Error, and move on to be shown ahead.
+ pass
+ reply_to_id = event.reply_to_msg_id or event.id
+ if any(item in cmd for item in KEEP_SAFE().All) and (
+ not (event.out or event.sender_id == ultroid_bot.uid)
+ ):
+ if event.sender_id in _ignore_eval:
+ return await xx.edit(
+ "`You cannot use this command now. Contact owner of this bot!`"
+ )
+ warning = await event.forward_to(udB.get_key("LOG_CHANNEL"))
+ await warning.reply(
+ f"Malicious Activities suspected by {inline_mention(await event.get_sender())}"
+ )
+ _ignore_eval.append(event.sender_id)
+ return await xx.edit(
+ "`Malicious Activities suspected⚠️!\nReported to owner. Aborted this request!`"
+ )
old_stderr = sys.stderr
old_stdout = sys.stdout
- redirected_output = sys.stdout = io.StringIO()
- redirected_error = sys.stderr = io.StringIO()
+ redirected_output = sys.stdout = StringIO()
+ redirected_error = sys.stderr = StringIO()
stdout, stderr, exc = None, None, None
- reply_to_id = event.message.id
try:
- await aexec(cmd, event)
+ value = await aexec(cmd, event)
except Exception:
exc = traceback.format_exc()
stdout = redirected_output.getvalue()
stderr = redirected_error.getvalue()
sys.stdout = old_stdout
sys.stderr = old_stderr
- evaluation = ""
- if exc:
- evaluation = exc
- elif stderr:
- evaluation = stderr
- elif stdout:
- evaluation = stdout
- else:
- evaluation = get_string("instu_4")
+ evaluation = exc or stderr or stdout or _parse_eval(value) or get_string("instu_4")
+ if silent:
+ if exc:
+ msg = f"• EVAL ERROR\n\n• CHAT: {get_display_name(event.chat)}
[{event.chat_id}
]"
+ msg += f"\n\n∆ CODE:\n{cmd}
\n\n∆ ERROR:\n{exc}
"
+ log_chat = udB.get_key("LOG_CHANNEL")
+ if len(msg) > 4000:
+ with BytesIO(msg.encode()) as out_file:
+ out_file.name = "Eval-Error.txt"
+ return await event.client.send_message(
+ log_chat, f"`{cmd}`", file=out_file
+ )
+ await event.client.send_message(log_chat, msg, parse_mode="html")
+ return
final_output = (
"__►__ **EVALPy**\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(
cmd,
@@ -139,7 +197,7 @@ async def _(event):
)
if len(final_output) > 4096:
ultd = final_output.replace("`", "").replace("**", "").replace("__", "")
- with io.BytesIO(str.encode(ultd)) as out_file:
+ with BytesIO(str.encode(ultd)) as out_file:
out_file.name = "eval.txt"
await event.client.send_file(
event.chat_id,
@@ -150,9 +208,13 @@ async def _(event):
caption=f"```{cmd}```" if len(cmd) < 998 else None,
reply_to=reply_to_id,
)
- await xx.delete()
- else:
- await xx.edit(final_output)
+ return await xx.delete()
+ await xx.edit(final_output)
+
+
+def _stringified(text, *args, **kwargs):
+ text = _parse_eval(text)
+ print(text, *args, **kwargs)
async def aexec(code, event):
@@ -162,7 +224,8 @@ async def aexec(code, event):
("async def __aexec(e, client): " + "\n message = event = e")
+ "\n reply = await event.get_reply_message()"
)
- + "\n chat = (await event.get_chat()).id"
+ + "\n chat = event.chat_id"
+ + "\n print = p = _stringified"
)
+ "".join(f"\n {l}" for l in code.split("\n"))
)
@@ -185,8 +248,8 @@ async def doie(e):
try:
match = match[1]
except IndexError:
- return await eor(e, get_string("devs_3"))
- msg = await eor(e, get_string("com_1"))
+ return await e.eor(get_string("devs_3"))
+ msg = await e.eor(get_string("com_1"))
if "main(" not in match:
new_m = "".join(" " * 4 + i + "\n" for i in match.split("\n"))
match = DUMMY_CPP.replace("!code", new_m)
@@ -199,7 +262,7 @@ async def doie(e):
os.remove("cpp-ultroid.cpp")
if os.path.exists("CppUltroid"):
os.remove("CppUltroid")
- with io.BytesIO(str.encode(o_cpp)) as out_file:
+ with BytesIO(str.encode(o_cpp)) as out_file:
out_file.name = "error.txt"
return await msg.reply(f"`{match}`", file=out_file)
return await eor(msg, o_cpp)
@@ -209,7 +272,7 @@ async def doie(e):
if m[1] != "":
o_cpp += f"\n\n**• Error :**\n`{m[1]}`"
if len(o_cpp) > 3000:
- with io.BytesIO(str.encode(o_cpp)) as out_file:
+ with BytesIO(str.encode(o_cpp)) as out_file:
out_file.name = "eval.txt"
await msg.reply(f"`{match}`", file=out_file)
else:
diff --git a/plugins/download_upload.py b/plugins/downloadupload.py
similarity index 80%
rename from plugins/download_upload.py
rename to plugins/downloadupload.py
index 1399b3d76f7bc00b643ff2db8ff54f9f2fa8d78d..445dd1a96d61dfa14a72e45e6d400edd2c900603 100644
--- a/plugins/download_upload.py
+++ b/plugins/downloadupload.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -19,7 +19,6 @@
• `{i}download (| filename)`
Download using DDL. Will autogenerate filename if not given.
-
"""
import asyncio
import glob
@@ -33,6 +32,7 @@ from telethon.errors.rpcerrorlist import MessageNotModifiedError
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from . import (
+ LOGS,
downloader,
eor,
fast_download,
@@ -50,7 +50,7 @@ from . import (
)
async def down(event):
matched = event.pattern_match.group(1)
- msg = await eor(event, get_string("udl_4"))
+ msg = await event.eor(get_string("udl_4"))
if not matched:
return await eor(msg, get_string("udl_5"), time=5)
try:
@@ -61,7 +61,7 @@ async def down(event):
filename = None
s_time = time.time()
try:
- filename = await fast_download(
+ filename, d = await fast_download(
link,
filename,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
@@ -75,8 +75,8 @@ async def down(event):
),
)
except InvalidURL:
- return await eor(msg, "`Invalid URL provided :(`", time=5)
- await eor(msg, f"`{filename} `downloaded.")
+ return await msg.eor("`Invalid URL provided :(`", time=5)
+ await msg.eor(f"`{filename}` `downloaded in {time_formatter(d*1000)}.`")
@ultroid_cmd(
@@ -84,14 +84,14 @@ async def down(event):
)
async def download(event):
if not event.reply_to_msg_id:
- return await eor(event, get_string("cvt_3"))
- xx = await eor(event, get_string("com_1"))
+ return await event.eor(get_string("cvt_3"))
+ xx = await event.eor(get_string("com_1"))
s = dt.now()
k = time.time()
if event.reply_to_msg_id:
ok = await event.get_reply_message()
if not ok.media:
- return await eor(xx, get_string("udl_1"), time=5)
+ return await xx.eor(get_string("udl_1"), time=5)
if hasattr(ok.media, "document"):
file = ok.media.document
mime_type = file.mime_type
@@ -129,7 +129,7 @@ async def download(event):
)
e = dt.now()
t = time_formatter(((e - s).seconds) * 1000)
- await eor(xx, get_string("udl_2").format(file_name, t))
+ await xx.eor(get_string("udl_2").format(file_name, t))
@ultroid_cmd(
@@ -138,7 +138,7 @@ async def download(event):
async def download(event):
if event.text[1:].startswith("ultroid"):
return
- xx = await eor(event, get_string("com_1"))
+ xx = await event.eor(get_string("com_1"))
hmm = event.pattern_match.group(1)
try:
kk = hmm.split(" | stream")[0]
@@ -152,10 +152,22 @@ async def download(event):
tt = time.time()
ko = kk
if not kk:
- return await eor(xx, get_string("udl_3"), time=5)
+ return await xx.eor(get_string("udl_3"), time=5)
+ if kk == ".env" or ".session" in kk:
+ return await eod(xx, get_string("udl_7"), time=5)
+ if not os.path.exists(kk):
+ try:
+ await event.client.send_file(
+ event.chat_id, file=kk, reply_to=event.reply_to_msg_id
+ )
+ await xx.try_delete()
+ return
+ except Exception as er:
+ LOGS.exception(er)
+ return await xx.eor("File doesn't exists or path is incorrect!", time=5)
if os.path.isdir(kk):
if not os.listdir(kk):
- return await eor(xx, get_string("udl_6"), time=5)
+ return await xx.eor(get_string("udl_6"), time=5)
ok = glob.glob(f"{kk}/*")
kk = [*sorted(ok)]
for kk in kk:
@@ -166,10 +178,7 @@ async def download(event):
except MessageNotModifiedError as err:
return await xx.edit(str(err))
title = kk.split("/")[-1]
- if (
- title.endswith((".mp3", ".m4a", ".opus", ".ogg", ".flac"))
- and " | stream" in hmm
- ):
+ if " | stream" in hmm:
data = await metadata(res.name)
wi = data["width"]
hi = data["height"]
@@ -185,38 +194,43 @@ async def download(event):
attributes = [
DocumentAttributeAudio(
duration=duration,
- title=title.split(".")[0],
+ title=".".join(title.split(".")[:-1]),
performer=artist,
)
]
+
else:
- attributes = None
+ attributes = []
try:
await event.client.send_file(
event.chat_id,
res,
- caption=f"`{kk}`",
+ caption=f"`{title}`",
+ reply_to=event.reply_to_msg_id,
attributes=attributes,
supports_streaming=True,
thumb="resources/extras/ultroid.jpg",
)
- except BaseException:
+ except BaseException as er:
+ LOGS.exception(er)
await event.client.send_file(
event.chat_id,
res,
- caption=f"`{kk}`",
+ caption=f"`{title}`",
+ reply_to=event.reply_to_msg_id,
thumb="resources/extras/ultroid.jpg",
)
else:
await event.client.send_file(
event.chat_id,
res,
- caption=f"`{kk}`",
+ caption=f"`{title}`",
+ reply_to=event.reply_to_msg_id,
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
except Exception as ve:
- return await eor(xx, str(ve))
+ return await xx.eor(str(ve))
else:
try:
try:
@@ -253,14 +267,17 @@ async def download(event):
res,
caption=f"`{title}`",
attributes=attributes,
+ reply_to=event.reply_to_msg_id,
supports_streaming=True,
thumb="resources/extras/ultroid.jpg",
)
- except BaseException:
+ except BaseException as er:
+ LOGS.exception(er)
await event.client.send_file(
event.chat_id,
res,
caption=f"`{title}`",
+ reply_to=event.reply_to_msg_id,
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
@@ -269,11 +286,12 @@ async def download(event):
event.chat_id,
res,
caption=f"`{title}`",
+ reply_to=event.reply_to_msg_id,
force_document=True,
thumb="resources/extras/ultroid.jpg",
)
except Exception as ve:
- return await eor(xx, str(ve))
+ return await xx.eor(str(ve))
e = dt.now()
t = time_formatter(((e - s).seconds) * 1000)
if os.path.isdir(ko):
@@ -289,4 +307,4 @@ async def download(event):
f"Uploaded `{ko}` Folder, Total - `{c}` files of `{humanbytes(size)}` in `{t}`",
)
else:
- await eor(xx, f"Uploaded `{ko}` in `{t}`")
+ await xx.eor(f"Uploaded `{ko}` in `{t}`")
diff --git a/plugins/echo.py b/plugins/echo.py
index dd12b94cd5a7839418f1289af6f5b2e4855bee6d..041664d60cf17e28023a53de9919b29b3ce3d5c1 100644
--- a/plugins/echo.py
+++ b/plugins/echo.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -15,13 +15,12 @@
•`{i}listecho `
To Get list.
-
"""
from pyUltroid.dB.echo_db import add_echo, check_echo, list_echo, rem_echo
from telethon.utils import get_display_name
-from . import LOGS, eor, events, ultroid_bot, ultroid_cmd
+from . import LOGS, events, ultroid_bot, ultroid_cmd
@ultroid_cmd(pattern="addecho ?(.*)")
@@ -38,13 +37,13 @@ async def echo(e):
else:
user = int(user)
except BaseException:
- return await eor(e, "Reply To A user.", time=5)
+ return await e.eor("Reply To A user.", time=5)
if check_echo(e.chat_id, user):
- return await eor(e, "Echo already activated for this user.", time=5)
+ return await e.eor("Echo already activated for this user.", time=5)
add_echo(e.chat_id, user)
ok = await e.client.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
- await eor(e, f"Activated Echo For {user}.")
+ await e.eor(f"Activated Echo For {user}.")
@ultroid_cmd(pattern="remecho ?(.*)")
@@ -61,13 +60,13 @@ async def rm(e):
else:
user = int(user)
except BaseException:
- return await eor(e, "Reply To A User.", time=5)
+ return await e.eor("Reply To A User.", time=5)
if check_echo(e.chat_id, user):
rem_echo(e.chat_id, user)
ok = await e.client.get_entity(user)
user = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
- return await eor(e, f"Deactivated Echo For {user}.")
- await eor(e, "Echo not activated for this user")
+ return await e.eor(f"Deactivated Echo For {user}.")
+ await e.eor("Echo not activated for this user")
@ultroid_bot.on(events.NewMessage(incoming=True))
@@ -89,6 +88,6 @@ async def lstecho(e):
ok = await e.client.get_entity(int(x))
kk = f"[{get_display_name(ok)}](tg://user?id={ok.id})"
user += "•" + kk + "\n"
- await eor(e, user)
+ await e.eor(user)
else:
- await eor(e, "`List is Empty, For echo`", time=5)
+ await e.eor("`List is Empty, For echo`", time=5)
diff --git a/plugins/extra.py b/plugins/extra.py
index 44d7676f117258467cfeba7a9955258f994fcc38..6ebbce0cb9b3900916c1f380846c5b2149198829 100644
--- a/plugins/extra.py
+++ b/plugins/extra.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -21,38 +21,22 @@
"""
import asyncio
-from telethon.events import NewMessage as NewMsg
-
-from . import HNDLR, eor, get_string, ultroid_bot, ultroid_cmd
-
-_new_msgs = {}
-
-
-@ultroid_bot.on(
- NewMsg(
- outgoing=True,
- ),
-)
-async def newmsg(event):
- if event.message.message == f"{HNDLR}reply":
- return
- _new_msgs[event.chat_id] = event.message
+from . import get_string, ultroid_cmd
@ultroid_cmd(
pattern="del$",
- type=["official", "manager"],
+ manager=True,
)
async def delete_it(delme):
msg_src = await delme.get_reply_message()
- if msg_src:
- try:
- await msg_src.delete()
- await delme.delete()
- except Exception as e:
- await eor(
- delme, f"Couldn't delete the message.\n\n**ERROR:**\n`{e}`", time=5
- )
+ if not msg_src:
+ return
+ try:
+ await msg_src.delete()
+ await delme.delete()
+ except Exception as e:
+ await delme.eor(f"Couldn't delete the message.\n\n**ERROR:**\n`{e}`", time=5)
@ultroid_cmd(
@@ -62,8 +46,8 @@ async def copy(e):
reply = await e.get_reply_message()
if reply:
await reply.reply(reply)
- return await e.delete()
- await eor(e, get_string("ex_1"), time=5)
+ return await e.try_delete()
+ await e.eor(get_string("ex_1"), time=5)
@ultroid_cmd(
@@ -82,7 +66,7 @@ async def editer(edit):
pass
else:
i = 1
- async for message in edit.client.iter_messages(chat, ultroid_bot.uid):
+ async for message in edit.client.iter_messages(chat, from_user="me", limit=2):
if i == 2:
await message.edit(string)
await edit.delete()
@@ -94,9 +78,16 @@ async def editer(edit):
pattern="reply$",
)
async def _(e):
- if e.reply_to_msg_id and e.chat_id in _new_msgs:
- msg = _new_msgs[e.chat_id]
- chat = await e.get_input_chat()
+ if e.reply_to_msg_id:
+ chat = e.chat_id
+ try:
+ msg = (await e.client.get_messages(e.chat_id, limit=1, max_id=e.id))[0]
+ except IndexError:
+ return await e.eor(
+ "`You have previously sent no message to reply again...`", time=5
+ )
+ except BaseException as er:
+ return await e.eor(f"**ERROR:** `{er}`")
await asyncio.wait(
[
e.client.delete_messages(chat, [e.id, msg.id]),
@@ -104,4 +95,4 @@ async def _(e):
]
)
else:
- await e.delete()
+ await e.try_delete()
diff --git a/plugins/fakeaction.py b/plugins/fakeaction.py
index 043ac66f514d5f57624f453723d3dfe0462f0f5e..8d292bb031788bc23c09c69ebf6058e6ab0833a5 100644
--- a/plugins/fakeaction.py
+++ b/plugins/fakeaction.py
@@ -1,5 +1,5 @@
# Ultroid - UserBot
-# Copyright (C) 2021 TeamUltroid
+# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
@@ -19,6 +19,9 @@
• `{i}fgame