Added socks5 proxy support

This commit is contained in:
Joan
2024-03-24 20:40:44 +01:00
parent a7eb633760
commit c31e155c74
5 changed files with 52 additions and 19 deletions

View File

@@ -24,6 +24,11 @@ services:
- NR_HOST_INSIGHTS=${NR_HOST_INSIGHTS} - NR_HOST_INSIGHTS=${NR_HOST_INSIGHTS}
- NR_HOST_METRICS=${NR_HOST_METRICS} - NR_HOST_METRICS=${NR_HOST_METRICS}
- PROXY_SOCKS=${PROXY_SOCKS} - PROXY_SOCKS=${PROXY_SOCKS}
- TELEGRAM_PROXY=${TELEGRAM_PROXY}
- TELEGRAM_SOCKS_USER=${TELEGRAM_SOCKS_USER}
- TELEGRAM_SOCKS_PASSWORD=${TELEGRAM_SOCKS_PASSWORD}
- TELEGRAM_SOCKS_SERVER=${TELEGRAM_SOCKS_SERVER}
- TELEGRAM_SOCKS_PORT=${TELEGRAM_SOCKS_PORT}
networks: networks:
- wallamanta_homelabs - wallamanta_homelabs

View File

@@ -21,7 +21,17 @@ NR_HOST_METRICS = os.getenv("NR_HOST_METRICS")
PROXY_SOCKS = os.getenv("PROXY_SOCKS") PROXY_SOCKS = os.getenv("PROXY_SOCKS")
MAX_WORKERS = 12 MAX_WORKERS = 12
telegram_proxy = os.environ.get("TELEGRAM_PROXY") == '1'
if telegram_proxy:
telegram_socks_user = os.environ.get("TELEGRAM_SOCKS_USER")
telegram_socks_password = os.environ.get("TELEGRAM_SOCKS_PASSWORD")
telegram_socks_server = os.environ.get("TELEGRAM_SOCKS_SERVER")
telegram_socks_port = os.environ.get("TELEGRAM_SOCKS_PORT")
proxy_url = f"socks5://{telegram_socks_user}:{telegram_socks_password}@{telegram_socks_server}:{telegram_socks_port}"
CATEGORIES = {
}
CATEGORIES = { CATEGORIES = {
100: ["🚗 Coches 🚗"], 100: ["🚗 Coches 🚗"],

View File

@@ -12,7 +12,7 @@ from newrelic_telemetry_sdk import Event, EventClient, GaugeMetric, MetricClient
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
from datetime import datetime, timedelta, timezone, date from datetime import datetime, timedelta, timezone, date
from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application from telegram.ext import ApplicationBuilder
from telegram.constants import ParseMode from telegram.constants import ParseMode
# Enable logging # Enable logging
@@ -128,6 +128,13 @@ def send_message(telegram_user_id, message):
'chat_id': (None, telegram_user_id), 'chat_id': (None, telegram_user_id),
'text': (None, message), 'text': (None, message),
} }
if constants.telegram_proxy:
try:
requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendMessage', files=files, proxies=dict(https=constants.proxy_url))
except:
time.sleep(1)
requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendMessage', files=files, proxies=dict(https=constants.proxy_url))
else:
try: try:
requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendMessage', files=files) requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendMessage', files=files)
except: except:
@@ -179,11 +186,17 @@ def send_article(article, product):
'reply_markup': (None, json.dumps(keyboard)), 'reply_markup': (None, json.dumps(keyboard)),
} }
if constants.telegram_proxy:
response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files, proxies=dict(https=constants.proxy_url))
else:
response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files) response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files)
tries = 0 tries = 0
while response.status_code != 200: while response.status_code != 200:
logging.info(f"Error sending to Telegram, probably flood restricted. {product['product_name']} ({product['id']}) - ({walladb.get_user(product['telegram_user_id'])}) - {response.status_code}") logging.info(f"Error sending to Telegram, probably flood restricted. {product['product_name']} ({product['id']}) - ({walladb.get_user(product['telegram_user_id'])}) - {response.status_code}")
random_wait() random_wait()
if constants.telegram_proxy:
response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files, proxies=dict(https=constants.proxy_url))
else:
response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files) response = requests.post(f'https://api.telegram.org/bot{constants.TELEGRAM_TOKEN}/sendPhoto', files=files)
tries = tries + 1 tries = tries + 1
if tries > 5: if tries > 5:
@@ -355,9 +368,9 @@ def send_to_nr(article, product):
def send_statistics_to_nr(query_time, products_found, number_of_searches): def send_statistics_to_nr(query_time, products_found, number_of_searches):
metric_client = MetricClient(insert_key=constants.NEW_RELIC_INSERT_KEY, host=constants.NR_HOST_METRICS) metric_client = MetricClient(insert_key=constants.NEW_RELIC_INSERT_KEY, host=constants.NR_HOST_METRICS)
query_time = GaugeMetric("query_time", query_time, {"units": "Seconds"}) query_time = GaugeMetric("query_time_homelabs", query_time, {"units": "Seconds"})
products_found = GaugeMetric("products_found", products_found) products_found = GaugeMetric("products_found_homelabs", products_found)
number_of_searches = GaugeMetric("active_searches", number_of_searches) number_of_searches = GaugeMetric("active_searches_homelabs", number_of_searches)
batch = [query_time, products_found, number_of_searches] batch = [query_time, products_found, number_of_searches]
try: try:

View File

@@ -1,5 +1,4 @@
python-telegram-bot==20.4 python-telegram-bot[job-queue,socks]==21.0.1
python-telegram-bot[job-queue]==20.4
requests==2.31.0 requests==2.31.0
requests[socks]==2.31.0 requests[socks]==2.31.0
prettytable==3.6.0 prettytable==3.6.0

View File

@@ -10,7 +10,7 @@ import search_manager
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ForceReply from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ForceReply
from telegram.constants import ParseMode from telegram.constants import ParseMode
from telegram.ext import ( from telegram.ext import (
Application, ApplicationBuilder,
CallbackQueryHandler, CallbackQueryHandler,
CallbackContext, CallbackContext,
CommandHandler, CommandHandler,
@@ -27,7 +27,7 @@ ACTION, ADD_PRODUCT_NAME, ADD_PRODUCT_MIN_PRICE, ADD_PRODUCT_MAX_PRICE, \
ADD_PRODUCT_COORDS, ADD_PRODUCT_DISTANCE, REMOVE_PRODUCT, LIST, FINISH, CONTINUE_OR_FINISH = range(13) ADD_PRODUCT_COORDS, ADD_PRODUCT_DISTANCE, REMOVE_PRODUCT, LIST, FINISH, CONTINUE_OR_FINISH = range(13)
MAX_PRODUCTS_TESTING = 5 MAX_PRODUCTS_TESTING = 5
MAX_PRODUCTS_PREMIUM = 30 MAX_PRODUCTS_PREMIUM = 5
MAX_PRODUCTS_HOMELABS = 5 MAX_PRODUCTS_HOMELABS = 5
# Enable logging # Enable logging
@@ -401,11 +401,11 @@ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N
telegram_user_id = helpers.get_telegram_user_id(update) telegram_user_id = helpers.get_telegram_user_id(update)
telegram_user_name = helpers.get_telegram_user_name(update) telegram_user_name = helpers.get_telegram_user_name(update)
#if not walladb.is_user_valid(telegram_user_id): #if not walladb.is_user_valid(telegram_user_id):
message = f"Bienvenido a @wallamanta_homelabs_vip, usa el comando /help para más información."
if telegram_user_id < 0: if telegram_user_id < 0:
message = "Este bot no se puede usar en grupos." message = "Este bot no se puede usar en grupos."
elif walladb.get_user(telegram_user_id) == "NoName": elif walladb.is_user_premium(telegram_user_id):
walladb.enable_user(telegram_user_id, telegram_user_name) message = f"Bienvenido a @wallamanta_homelabs_vip, usa el comando /help para más información."
message = f"Bienvenido a @wallamanta, usa el comando /help para más información."
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message)) await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
async def add_to_db_and_send(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def add_to_db_and_send(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -480,7 +480,13 @@ def main()->None:
"""Start the bot.""" """Start the bot."""
# Create the Application and pass it your bot's token. # Create the Application and pass it your bot's token.
application = Application.builder().get_updates_http_version('1.1').http_version('1.1').token(constants.TELEGRAM_TOKEN).build() if constants.telegram_proxy:
logging.info("Creating application with socks5 proxy")
application = ApplicationBuilder().get_updates_http_version('1.1').http_version('1.1').token(constants.TELEGRAM_TOKEN).proxy(constants.proxy_url).get_updates_proxy(constants.proxy_url).build()
else:
logging.info("Creating application without socks5 proxy")
application = ApplicationBuilder().get_updates_http_version('1.1').http_version('1.1').token(constants.TELEGRAM_TOKEN).build()
p = threading.Thread(target=search_manager.work) p = threading.Thread(target=search_manager.work)
p.start() p.start()