Skip to content

Commit

Permalink
✨ feat: adding middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
joaroque committed Aug 5, 2023
1 parent 4c3e5e3 commit eb9f28f
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 9 deletions.
Binary file modified .DS_Store
Binary file not shown.
29 changes: 20 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import asyncio
import configparser
import json
import logging
import ssl
import configparser

import websockets
from telethon import TelegramClient
import logging
import websockets.exceptions
from telethon import TelegramClient

from utils.middleware import should_send

# Configuring the logging
logging.basicConfig(level=logging.INFO)

config = configparser.ConfigParser()
config.read("config.ini")

# Telegram settings
# Telegram settings
api_id = config.getint("TELEGRAM", "API_ID")
api_hash = config.get("TELEGRAM", "API_HASH")
client_name = config.get("TELEGRAM", "CLIENT_NAME")
Expand All @@ -27,10 +30,12 @@

client = TelegramClient(client_name, api_id, api_hash)


async def send_to_telegram(message):
await client.send_message(destination_channel, message)
logging.info(f"Message sent to Telegram: {message}")


async def heartbeat(ws, interval, last_sequence):
while True:
await asyncio.sleep(interval)
Expand All @@ -41,6 +46,7 @@ async def heartbeat(ws, interval, last_sequence):
await ws.send(json.dumps(payload))
logging.info("Heartbeat packet sent.")


async def identify(ws):
identify_payload = {
"op": 2,
Expand All @@ -56,17 +62,18 @@ async def identify(ws):
await ws.send(json.dumps(identify_payload))
logging.info("Identification sent.")


async def on_message(ws):
last_sequence = None
while True:
event = json.loads(await ws.recv())
logging.info(f"Event received: {event}")
op_code = event.get('op', None)

if op_code == 10:
interval = event['d']['heartbeat_interval'] / 1000
asyncio.create_task(heartbeat(ws, interval, last_sequence))

elif op_code == 0:
last_sequence = event.get('s', None)
event_type = event.get('t')
Expand All @@ -76,12 +83,15 @@ async def on_message(ws):
if channel_id == channel_id_to_monitor and message != '':
logging.info(f"Message received from Discord: {message}")

await send_to_telegram(f"{message}")

if should_send(message):
# comment this line if you dont want to use middlware
await send_to_telegram(f"{message}")

elif op_code == 9:
logging.info("Invalid session. Starting a new session...")
await identify(ws)


async def main():
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
Expand All @@ -93,7 +103,8 @@ async def main():
await identify(ws)
await on_message(ws)
except websockets.exceptions.ConnectionClosed as e:
logging.error(f"WebSocket connection closed unexpectedly: {e}. Reconnecting...")
logging.error(
f"WebSocket connection closed unexpectedly: {e}. Reconnecting...")
await asyncio.sleep(5)
continue

Expand Down
Binary file added screenshots/discord_auth_token.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added screenshots/telegram_apps.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions utils/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import re

"""
Feel free to improve this code.
I do something basic that suits my needs.
"""


important_keywords = [
"EURGBP",
"AUDJPY",
"EURAUD",
"EURCHF",
"AUDNZD",
"NZDJPY",
"GBPAUD",
"GBPCAD",
"EURNZD",
"AUDCAD",
"GBPCHF",
"AUDCHF",
"EURCAD",
"CADJPY",
"GBPNZD",
"CADCHF",
"CHFJPY",
"NZDCAD",
"NZDCHF",
"XAUUSD",
"EURUSD",
"USDJPY",
"GBPUSD",
"AUDUSD",
"USDCAD",
"USDCHF",
"NZDUSD",
"EURJPY",
"GBPJPY"
]


def should_send(message):
cleaned_message = re.sub(r'\s+AT\s+\d+\.\d+\s+\(.*\)', '', message)

if any(keyword in cleaned_message.upper() for keyword in important_keywords):
return cleaned_message.strip()

0 comments on commit eb9f28f

Please sign in to comment.