Skip to content
This repository has been archived by the owner on May 15, 2021. It is now read-only.

Commit

Permalink
Bugfix (#102)
Browse files Browse the repository at this point in the history
* Added Error msg if iytdl search result is None

* trying to fix bot fwd

- added progress  for broadcast
- added context manager for load()
- replaced json with -> faster ujson
- minor tweaks

* fixed bot forwards

* Added missing Callbacks

* Fixed Thumb issue in  iytdl

* async async async async (#101)

boi if you dont....

* Update kang.py

Co-authored-by: ポキ <aman_a@aol.com>
  • Loading branch information
code-rgb and CustomIcon authored Jan 10, 2021
1 parent d27bd26 commit c06b271
Show file tree
Hide file tree
Showing 14 changed files with 348 additions and 187 deletions.
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ instaloader>=4.5.5
motor>=2.3.0
natsort>=7.1.0
oauth2client>=4.1.3
Pillow==7.1.0
Pillow==8.0
psutil>=5.7.3
pybase64>=1.1.1
git+https://github.com/code-rgb/pyrogram.git@x21
Expand All @@ -38,7 +38,7 @@ tgcrypto
urbandict>=0.5
wget>=3.2
wikipedia>=1.4.0
youtube_dl>=2020.12.12
youtube_dl>=2021.1.8
git+https://github.com/Nekos-life/Async-nekos.life-wrapper
PyYAML>=5.3.1
pymediainfo>=5.0.3
Expand Down
2 changes: 1 addition & 1 deletion runtime.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
python-3.8.7
python-3.8.7
9 changes: 6 additions & 3 deletions userge/core/methods/utils/restart.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
class Restart(RawClient): # pylint: disable=missing-class-docstring
async def restart(self, update_req: bool = False) -> None: # pylint: disable=arguments-differ
""" Restart the AbstractUserge """
_LOG.info(_LOG_STR, "Restarting Userge")
_LOG.info(_LOG_STR, "Restarting USERGE-X")
await self.stop()
try:
c_p = psutil.Process(os.getpid())
Expand All @@ -35,6 +35,9 @@ async def restart(self, update_req: bool = False) -> None: # pylint: disable=ar
print(_LOG_STR % c_e)
if update_req:
print(_LOG_STR % "Installing Requirements...")
os.system("pip3 install -U pip && pip3 install -r requirements.txt") # nosec
# nosec
os.system(
"pip3 install -U pip && pip3 install --no-cache-dir -r requirements.txt"
)
os.execl(sys.executable, sys.executable, '-m', 'userge') # nosec
sys.exit()
sys.exit()
2 changes: 0 additions & 2 deletions userge/plugins/bot/alive.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,13 @@
@userge.on_cmd("alive", about={"header": "Just For Fun"}, allow_channels=False)
async def alive_inline(message: Message):
bot = await userge.bot.get_me()

try:
x = await userge.get_inline_bot_results(bot.username, "alive")
y = await userge.send_inline_bot_result(
chat_id=message.chat.id, query_id=x.query_id, result_id=x.results[0].id
)
except (Forbidden, BadRequest) as ex:
return await message.err(str(ex), del_in=5)

await message.delete()
await asyncio.sleep(90)
await userge.delete_messages(message.chat.id, y.updates[0].id)
Expand Down
86 changes: 56 additions & 30 deletions userge/plugins/bot/bot_forwards.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
"""Bot Message forwarding"""

import asyncio
import json
import os

import ujson
from pyrogram import filters
from pyrogram.errors import BadRequest, FloodWait, MessageIdInvalid
from pyrogram.errors import BadRequest, FloodWait, MessageIdInvalid, UserIsBlocked

from userge import Config, Message, get_collection, userge
from userge.utils import mention_html
Expand Down Expand Up @@ -71,6 +71,12 @@ async def forward_bot(_, message: Message):
Config.OWNER_ID[0], message.chat.id, msg_id
)
except MessageIdInvalid:
await CHANNEL.log(
f"**ERROR**: can't send message to __ID__: {Config.OWNER_ID[0]}\nNote: message will be send to the first id in `OWNER_ID` only!"
)
return
except UserIsBlocked:
await CHANNEL.log("**ERROR**: You Blocked your Bot !")
return
update = bool(os.path.exists(PATH))
await dumper(msg_owner.message_id, message.from_user.id, update)
Expand All @@ -93,15 +99,21 @@ async def forward_reply(_, message: Message):
if not replied.forward_sender_name:
return
try:
data = json.load(open(PATH))
with open(PATH) as f:
data = ujson.load(f)
user_id = data[0][str(replied.message_id)]
if to_copy:
await userge.bot.copy_message(user_id, message.chat.id, msg_id)
await userge.bot.copy_message(
chat_id=user_id, from_chat_id=message.chat.id, message_id=msg_id
)
else:
await userge.bot.forward_messages(user_id, message.chat.id, msg_id)
await userge.bot.forward_messages(
chat_id=user_id, from_chat_id=message.chat.id, message_id=msg_id
)
except BadRequest:
return
except:
except Exception:
# await CHANNEL.log(str(e))
await userge.bot.send_message(
message.chat.id,
"`You can't reply to old messages with if user's"
Expand All @@ -114,9 +126,13 @@ async def forward_reply(_, message: Message):
if to_user.id in Config.OWNER_ID:
return
if to_copy:
await userge.bot.copy_message(to_user.id, message.chat.id, msg_id)
await userge.bot.copy_message(
chat_id=user_id, from_chat_id=message.chat.id, message_id=msg_id
)
else:
await userge.bot.forward_messages(to_user.id, message.chat.id, msg_id)
await userge.bot.forward_messages(
chat_id=user_id, from_chat_id=message.chat.id, message_id=msg_id
)

# Based - https://github.com/UsergeTeam/Userge/.../gban.py

Expand Down Expand Up @@ -168,12 +184,12 @@ async def bot_ban_(_, message: Message):
BOT_BAN.insert_one(
{"firstname": firstname, "user_id": user_id, "reason": reason}
),
await start_ban.edit(
start_ban.edit(
r"\\**#Banned From Bot PM_User**//"
f"\n\n**First Name:** [{firstname}](tg://user?id={user_id})\n"
f"**User ID:** `{user_id}`\n**Reason:** `{reason}`"
),
await userge.bot.send_message(user_id, banned_msg),
userge.bot.send_message(user_id, banned_msg),
)

@userge.bot.on_message(
Expand Down Expand Up @@ -201,24 +217,33 @@ async def broadcast_(_, message: Message):
b_id, "🔊 You received a **new** Broadcast."
)
if to_copy:
await userge.bot.copy_message(b_id, message.chat.id, b_msg)
await userge.bot.copy_message(
chat_id=b_id, from_chat_id=message.chat.id, message_id=b_msg
)
else:
await userge.bot.forward_messages(b_id, message.chat.id, b_msg)

await userge.bot.forward_messages(
chat_id=b_id, from_chat_id=message.chat.id, message_id=b_msg
)
except FloodWait as e:
await asyncio.sleep(e.x)
await asyncio.sleep(e.x + 5)
except BadRequest:
blocked_users.append(
b_id
) # Collect the user id and removing them later
else:
count += 1
if count % 10 == 0:
try:
await br_cast.edit(
f"`Processing ...`\n> Success: (**{count}**)"
)
except FloodWait as e:
await asyncio.sleep(e.x + 5)

b_info = f"🔊 **Successfully Broadcasted This Message to** `{count} users`"
if len(blocked_users) != 0:
b_info += f"\n\n😕 {len(blocked_users)} users blocked your bot recently"
await br_cast.edit(b_info)
await CHANNEL.log(b_info)
await br_cast.edit(b_info, log=__name__)
if blocked_users:
for buser in blocked_users:
await BOT_START.find_one_and_delete({"user_id": buser})
Expand All @@ -241,8 +266,9 @@ async def uinfo_(_, message: Message):
usr = None
if replied.forward_sender_name:
try:
data = json.load(open(PATH))
user_id = data[0].get(str(replied.message_id), None)
with open(PATH) as f:
data = ujson.load(f)
user_id = data[0].get(str(replied.message_id))
usr = (await userge.bot.get_users(user_id)).mention
except (BadRequest, FileNotFoundError):
user_id = None
Expand All @@ -255,19 +281,22 @@ async def uinfo_(_, message: Message):
await info_msg.edit(f"<b><u>User Info</u></b>\n\n__ID__ `{user_id}`\n👤: {usr}")


async def dumper(a, b, update):
async def dumper(a: int, b: int, update: bool):
if update:
data = json.load(open(PATH)) # load
with open(PATH) as f:
data = ujson.load(f)
data[0].update({a: b}) # Update
else:
data = [{a: b}]

json.dump(data, open(PATH, "w")) # Dump
with open(PATH, "w") as outfile:
ujson.dump(data, outfile)


def extract_content(msg: Message): # Modified a bound method
id_reason = msg.matches[0].group(1)
replied = msg.reply_to_message
user_id, reason = None, None
if replied:
fwd = replied.forward_from
if fwd and id_reason:
Expand All @@ -276,10 +305,12 @@ def extract_content(msg: Message): # Modified a bound method
if replied.forward_sender_name and id_reason:
reason = id_reason
try:
data = json.load(open(PATH))
user_id = data[0][str(replied.message_id)]
except:
user_id = None
with open(PATH) as f:
data = ujson.load(f)
except FileNotFoundError:
pass
else:
user_id = data[0].get(str(replied.message_id))
else:
if id_reason:
data = id_reason.split(maxsplit=1)
Expand All @@ -288,17 +319,12 @@ def extract_content(msg: Message): # Modified a bound method
user, reason = data
elif len(data) == 1:
user = data[0]
reason = None
# if user id, convert it to integer
if user.isdigit():
user_id = int(user)

# User @ Mention.
if user.startswith("@"):
user_id = user
else:
user_id = None # just in case :p
reason = None
return user_id, reason


Expand Down
9 changes: 6 additions & 3 deletions userge/plugins/bot/opinion.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ async def choice_cb(_, c_q: CallbackQuery):
opinion_id = c_q.matches[0].group(2)
ids = c_q.from_user.id
counter = c_q.matches[0].group(1)
data = ujson.load(open(PATH))
with open(PATH) as f:
data = ujson.load(f)
view_data = data[str(opinion_id)]
agree_data = "👍"
disagree_data = "👎"
Expand Down Expand Up @@ -69,7 +70,8 @@ async def choice_cb(_, c_q: CallbackQuery):
disagree = view_data[1]["disagree"] + 1
view_data[1] = {"agree": agree, "disagree": disagree}
data[str(opinion_id)] = view_data
ujson.dump(data, open(PATH, "w"))
with open(PATH, "w") as outfile:
ujson.dump(data, outfile)
else:
if len(view_data) == 1:
# Answering Query First then moving forward
Expand All @@ -80,7 +82,8 @@ async def choice_cb(_, c_q: CallbackQuery):
if counter == "n":
view_data = [{ids: "n"}, {"agree": 0, "disagree": 1}]
data[str(opinion_id)] = view_data
ujson.dump(data, open(PATH, "w"))
with open(PATH, "w") as outfile:
ujson.dump(data, outfile)

agree_data += f" {view_data[1]['agree']}"
disagree_data += f" {view_data[1]['disagree']}"
Expand Down
Loading

0 comments on commit c06b271

Please sign in to comment.