Skip to content

Commit

Permalink
gban fix [ UsergeBotNotFound error ]
Browse files Browse the repository at this point in the history
update required vars when deploy (now only need 5 vars)

add only_admins option to on_cmd decorator

redesined traceback log template

fixed showing improper logging name in logging channel

+ optimize init logs
  • Loading branch information
rking32 committed Jul 20, 2020
1 parent 730b254 commit 75defae
Show file tree
Hide file tree
Showing 15 changed files with 140 additions and 79 deletions.
35 changes: 14 additions & 21 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,16 @@
"description": "Mongodb url from https://cloud.mongodb.com/"
},
"G_DRIVE_CLIENT_ID": {
"description": "Googel Drive API Keys from https://console.developers.google.com/"
"description": "Googel Drive API Keys from https://console.developers.google.com/",
"required": false
},
"G_DRIVE_CLIENT_SECRET": {
"description": "Googel Drive API Keys from https://console.developers.google.com/"
"description": "Googel Drive API Keys from https://console.developers.google.com/",
"required": false
},
"G_DRIVE_IS_TD": {
"description": "Set True if it is TeamDrive",
"value": "True"
"description": "Set true if it is TeamDrive",
"required": false
},
"LOG_CHANNEL_ID": {
"description": "Telegram Log Channel ID"
Expand Down Expand Up @@ -127,24 +129,15 @@
"required": false
}
},
"addons": [
],
"addons": [],
"buildpacks": [
{
"url": "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git"
}, {
"url": "https://github.com/HasibulKabir/heroku-buildpack-rarlab.git"
}, {
"url": "https://github.com/opendoor-labs/heroku-buildpack-p7zip"
}, {
"url": "https://github.com/rking32/heroku-buildpack-google-chrome"
}, {
"url": "https://github.com/rking32/heroku-buildpack-chromedriver"
}, {
"url": "https://github.com/heroku/heroku-buildpack-apt.git"
}, {
"url": "heroku/python"
}
{"url": "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git"},
{"url": "https://github.com/HasibulKabir/heroku-buildpack-rarlab.git"},
{"url": "https://github.com/opendoor-labs/heroku-buildpack-p7zip"},
{"url": "https://github.com/rking32/heroku-buildpack-google-chrome"},
{"url": "https://github.com/rking32/heroku-buildpack-chromedriver"},
{"url": "https://github.com/heroku/heroku-buildpack-apt.git"},
{"url": "heroku/python"}
],
"formation": {
"worker": {
Expand Down
27 changes: 15 additions & 12 deletions config.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
_____REMOVE_____THIS_____LINE_____=true


# ----------- REQUIRED ----------- #


# Get them from https://my.telegram.org/
API_ID=""
API_HASH=""
Expand All @@ -26,24 +29,15 @@ HU_STRING_SESSION=""
DATABASE_URL=""


# Googel Drive API Keys from https://console.developers.google.com/
G_DRIVE_CLIENT_ID=""
G_DRIVE_CLIENT_SECRET=""


# Set true if it is TeamDrive
G_DRIVE_IS_TD=false


# Telegram Log Channel ID
LOG_CHANNEL_ID=""


# Set true if your like to use unofficial plugins
LOAD_UNOFFICIAL_PLUGINS=false
# ----------- OPTIONAL ----------- #


# ----------- OPTIONAL ----------- #
# Set true if your like to use unofficial plugins
LOAD_UNOFFICIAL_PLUGINS=false


# Get this from https://t.me/botfather if you like to use userge as a bot
Expand All @@ -58,6 +52,15 @@ OWNER_ID=""
WORKERS=4


# Googel Drive API Keys from https://console.developers.google.com/
G_DRIVE_CLIENT_ID=""
G_DRIVE_CLIENT_SECRET=""


# Set true if it is TeamDrive
G_DRIVE_IS_TD=false


# Index link for gdrive
G_DRIVE_INDEX_LINK=""

Expand Down
8 changes: 6 additions & 2 deletions init/logbot/core/api.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ _getResponse() {
let _mid+=1
fi
else
quit "invalid request ! caused by (core.Api.$FUNCNAME)\n$rawUpdate"
local errcode=$(echo $rawUpdate | jq .error_code)
local desc=$(echo $rawUpdate | jq .description)
quit "invalid request ! (caused by core.api.$FUNCNAME)
\terror_code : [$errcode]
\tdescription : $desc"
fi
fi
}
Expand All @@ -51,7 +55,7 @@ getLastMessage() {
if test ${#_allMessages[@]} -gt 0; then
${_allMessages[-1]}.$1 "$2"
elif [[ -n $BOT_TOKEN && -n $LOG_CHANNEL_ID ]]; then
log "first sendMessage ! caused by (core.Api.$FUNCNAME)\n"$2""
log "first sendMessage ! (caused by \"core.api.$FUNCNAME\")\n"$2""
else
log "$2"
fi
Expand Down
4 changes: 2 additions & 2 deletions init/logbot/methods/methods.sh
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ _polling() {
test -z $cmd && break;;
esac
done
log "Ended LogBot Polling !"
log "LogBot Polling Ended with SIGTERM !"
exit 0
}

declare -i _to=1

_pollsleep() {
let _to+=1
log "sleeping ($_to) caused by (LogBot.polling)"
log "sleeping (${_to}s) (caused by \"LogBot.polling\")"
sleep $_to
}
5 changes: 3 additions & 2 deletions init/utils.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ declare -r pVer=$(sed -E 's/\w+ ([2-3])\.([0-9]+)\.([0-9]+)/\1.\2.\3/g' < <(pyth

log() {
local text="$*"
test ${#text} -gt 0 && test ${text::1} != '~' && echo -e "[LOGS] >>> ${text#\~}"
test ${#text} -gt 0 && test ${text::1} != '~' \
&& echo -e "[$(date +'%d-%b-%y %H:%M:%S') - INIT] - ${text#\~}"
}

quit() {
local err="\t:: ERROR :: $1 -> Exiting ..."
local err="\t:: ERROR :: $1\nExiting With SIGTERM ..."
if (( getMessageCount )); then
replyLastMessage "$err"
else
Expand Down
9 changes: 9 additions & 0 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ async def _complete_init_tasks() -> None:


class _AbstractUserge(Methods, RawClient):
@property
def is_bot(self) -> bool:
""" returns client is bot or not """
if self._bot is not None:
return hasattr(self, 'ubot')
if Config.BOT_TOKEN:
return True
return False

@property
def uptime(self) -> str:
""" returns userge uptime """
Expand Down
6 changes: 6 additions & 0 deletions userge/core/methods/decorators/on_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def on_cmd(self,
name: str = '',
trigger: str = Config.CMD_TRIGGER,
filter_me: bool = True,
only_admins: bool = False,
allow_private: bool = True,
allow_bots: bool = True,
allow_groups: bool = True,
Expand Down Expand Up @@ -71,6 +72,9 @@ def on_cmd(self,
filter_me (``bool``, *optional*):
If ``False``, anyone can access, defaults to True.
only_admins (``bool``, *optional*):
If ``True``, client should be an admin, defaults to False.
allow_private (``bool``, *optional*):
If ``False``, prohibit private chats, defaults to True.
Expand Down Expand Up @@ -110,6 +114,8 @@ def on_cmd(self,
pattern += r"(?:\s([\S\s]+))?$"
cmd = types.raw.Command(self, cname, about, group, allow_via_bot)
scope: List[str] = []
if only_admins:
scope.append('admin')
if allow_private:
scope.append('private')
if allow_bots:
Expand Down
84 changes: 59 additions & 25 deletions userge/core/methods/decorators/raw_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import time
import asyncio
from traceback import format_exc
from functools import partial
from typing import List, Union, Any, Callable, Optional

from pyrogram import (
Expand All @@ -28,9 +29,29 @@
_LOG_STR = "<<<! ::::: %s ::::: !>>>"

_PYROFUNC = Callable[['types.bound.Message'], Any]
_B_CMN_CHT: List[int] = []
_START_TO = time.time()

_B_ID = 0
_B_CMN_CHT: List[int] = []
_B_AD_CHT: List[int] = []
_B_NM_CHT: List[int] = []

_U_ID = 0
_U_AD_CHT: List[int] = []
_U_NM_CHT: List[int] = []


async def _raise_func(r_c: Union['_client.Userge', '_client._UsergeBot'],
chat_id: int, message_id: int, text: str) -> None:
try:
_sent = await r_c.send_message(
chat_id=chat_id,
text=f"< **ERROR** : {text} ! >",
reply_to_message_id=message_id)
await asyncio.sleep(5)
await _sent.delete()
except ChatAdminRequired:
pass


async def _get_bot_chats(r_c: Union['_client.Userge', '_client._UsergeBot'],
Expand All @@ -54,6 +75,32 @@ async def _get_bot_chats(r_c: Union['_client.Userge', '_client._UsergeBot'],
return _B_CMN_CHT


async def _is_admin(r_c: Union['_client.Userge', '_client._UsergeBot'],
r_m: RawMessage) -> bool:
global _U_ID, _B_ID # pylint: disable=global-statement
if r_m.chat.type in ("private", "bot"):
return False
if isinstance(r_c, _client.Userge):
if not _U_ID:
_U_ID = (await r_c.get_me()).id
if r_m.chat.id not in _U_AD_CHT + _U_NM_CHT:
user = await r_m.chat.get_member(_U_ID)
if user.status in ("creator", "administrator"):
_U_AD_CHT.append(r_m.chat.id)
else:
_U_NM_CHT.append(r_m.chat.id)
return r_m.chat.id in _U_AD_CHT
if not _B_ID:
_B_ID = (await r_c.get_me()).id
if r_m.chat.id not in _B_AD_CHT + _B_NM_CHT:
bot = await r_m.chat.get_member(_B_ID)
if bot.status in ("creator", "administrator"):
_B_AD_CHT.append(r_m.chat.id)
else:
_B_NM_CHT.append(r_m.chat.id)
return r_m.chat.id in _B_AD_CHT


class RawDecorator(RawClient):
""" userge raw decoretor """
_PYRORETTYPE = Callable[[_PYROFUNC], _PYROFUNC]
Expand Down Expand Up @@ -88,37 +135,24 @@ async def template(r_c: Union['_client.Userge', '_client._UsergeBot'],
if r_m.chat.id in await _get_bot_chats(r_c, r_m):
if isinstance(r_c, _client.Userge):
return
if isinstance(flt, types.raw.Command) and r_m.chat and (r_m.chat.type not in scope):
try:
_sent = await r_c.send_message(
r_m.chat.id,
"**ERROR** : `Sorry!, this command not supported "
f"in this chat type [{r_m.chat.type}] !`",
reply_to_message_id=r_m.message_id)
await asyncio.sleep(5)
await _sent.delete()
except ChatAdminRequired:
pass
_raise = partial(_raise_func, r_c, r_m.chat.id, r_m.message_id)
if isinstance(flt, types.raw.Command) and r_m.chat and r_m.chat.type not in scope:
await _raise(f"`invalid chat type [{r_m.chat.type}]`")
elif (isinstance(flt, types.raw.Command) and r_m.chat and r_m.from_user
and 'admin' in scope and not await _is_admin(r_c, r_m)):
await _raise("`chat admin required`")
else:
try:
await func(types.bound.Message(r_c, r_m, **kwargs))
except (StopPropagation, ContinuePropagation): # pylint: disable=W0706
raise
except Exception as f_e: # pylint: disable=broad-except
_LOG.exception(_LOG_STR, f_e)
await self._channel.log("#ERROR #TRACEBACK\n\n"
f"**Module** : `{func.__module__}`\n"
f"**Function** : `{func.__name__}`\n"
f"**Traceback** : ```{format_exc().strip()}```")
try:
_sent = await r_c.send_message(
r_m.chat.id,
f"**ERROR** : `{f_e}`\n__see logs for more info !__",
reply_to_message_id=r_m.message_id)
await asyncio.sleep(5)
await _sent.delete()
except ChatAdminRequired:
pass
await self._channel.log(f"**PLUGIN** : `{func.__module__}`\n"
f"**FUNCTION** : `{func.__name__}`\n"
f"\n```{format_exc().strip()}```",
"TRACEBACK")
await _raise(f"`{f_e}`\n__see logs for more info__")
_LOG.debug(_LOG_STR, f"Loading => [ async def {func.__name__}(message) ] "
f"from {func.__module__} `{log}`")
flt.update(func, MessageHandler(template, filters))
Expand Down
5 changes: 3 additions & 2 deletions userge/core/methods/messages/edit_message_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ async def edit_message_text(self, # pylint: disable=arguments-differ
disable_web_page_preview=disable_web_page_preview,
reply_markup=reply_markup)
if log:
args = [msg]
if isinstance(log, str):
self._channel.update(log)
await self._channel.fwd_msg(msg)
args.append(log)
await self._channel.fwd_msg(*args)
del_in = del_in or Config.MSG_DELETE_TIMEOUT
if del_in > 0:
await asyncio.sleep(del_in)
Expand Down
5 changes: 3 additions & 2 deletions userge/core/methods/messages/send_as_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ async def send_as_file(self,
reply_to_message_id=reply_to_message_id)
os.remove(filename)
if log:
args = [msg]
if isinstance(log, str):
self._channel.update(log)
await self._channel.fwd_msg(msg)
args.append(log)
await self._channel.fwd_msg(*args)
return types.bound.Message(self, msg)
5 changes: 3 additions & 2 deletions userge/core/methods/messages/send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ async def send_message(self, # pylint: disable=arguments-differ
schedule_date=schedule_date,
reply_markup=reply_markup)
if log:
args = [msg]
if isinstance(log, str):
self._channel.update(log)
await self._channel.fwd_msg(msg)
args.append(log)
await self._channel.fwd_msg(*args)
del_in = del_in or Config.MSG_DELETE_TIMEOUT
if del_in > 0:
await asyncio.sleep(del_in)
Expand Down
2 changes: 0 additions & 2 deletions userge/core/types/bound/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

from userge import logging
from ... import client as _client # pylint: disable=unused-import
from ..new import ChannelLogger

_CANCEL_LIST: List[int] = []
_ERROR_MSG_DELETE_TIMEOUT = 5
Expand Down Expand Up @@ -52,7 +51,6 @@ def __init__(self,
self.reply_to_message: Optional[RawMessage]
if self.reply_to_message:
self.reply_to_message = self.__class__(self._client, self.reply_to_message)
self._channel = ChannelLogger(client, "CORE")
self._filtered = False
self._process_canceled = False
self._filtered_input_str: str = ''
Expand Down
Loading

0 comments on commit 75defae

Please sign in to comment.