forked from runetech0/discord-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
234 lines (198 loc) · 8.66 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/python3
''''
Author: Rehman Ali
Python version used: Python3
NOTE: Please don't mess with code if you don't understand what you are doing.
'''
import os
import socks
import discord
from discord import errors
import requests
import socket
import re
import logging
from box import Box as box
from colorama import Back, Fore, init, Style
from aiohttp import client_exceptions as clientExcps
from dotenv import load_dotenv
load_dotenv()
init(autoreset=True)
# Lines 26-37 have been added to mimic the use of the conf.py in the form of env variables
class Config:
USER_DISCORD_TOKEN = os.getenv("USER_DISCORD_TOKEN")
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
TELEGRAM_RECEIVER_CHAT_ID = os.getenv("TELEGRAM_RECEIVER_CHAT_ID")
PROXY = False
serversList = {
"Schrödinger Hat": [
"general-contributors",
]
}
config = Config()
colorSchemes = {
'SUCCESS': f"{Back.GREEN}{Fore.BLACK}{Style.NORMAL}",
'FAILURE': f"{Back.RED}{Fore.WHITE}{Style.BRIGHT}",
'WARNING': f"{Back.YELLOW}{Fore.BLACK}{Style.BRIGHT}",
'RESET': f"{Style.RESET_ALL}"
}
colorSchemes = box(colorSchemes)
logging.basicConfig(format=f'{colorSchemes.FAILURE}[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.ERROR)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
baseUrl = f"https://api.telegram.org/bot{config.TELEGRAM_BOT_TOKEN}"
def replaceMentions(mentions, msg, channel):
if channel:
for ch in mentions:
# msg = msg.replace(str(f"#{ch.id}"), '')
msg = re.sub(f"<#{ch.id}>", '', msg)
msg = re.sub(f"<{ch.id}>", '', msg)
msg = re.sub(f"<*{ch.id}>", '', msg)
msg = re.sub(f"<*{ch.id}*>", '', msg)
msg = re.sub(f"<{ch.id}*>", '', msg)
elif not channel:
for member in mentions:
msg = re.sub(f"<@{member.id}>", '', msg)
msg = re.sub(f"<@!{member.id}>", '', msg)
msg = re.sub(f"<{member.id}>", '', msg)
msg = re.sub(f"<*{member.id}*>", '', msg)
msg = re.sub(f"<{member.id}*>", '', msg)
msg = re.sub(f"<*{member.id}>", '', msg)
return str(msg)
def removeTags(msg):
msg = re.sub(r"@\w*", '', msg)
msg = requests.utils.quote(msg)
print(f"{colorSchemes.SUCCESS}Quoted message: {msg}")
return msg
def isPhoto(url):
imgExts = ["png", "jpg", "jpeg", "webp"]
if any(ext in url for ext in imgExts):
return True
else:
return False
def isVideo(url):
vidExts = ["mp4", "MP4", "mkv"]
if any(ext in url for ext in vidExts):
return True
else:
return False
def isDoc(url):
docExts = ["zip", "pdf", "gif"]
if any(ext in url for ext in docExts):
return True
else:
return False
def matchChannel(channel, list):
found=False
for ch in list:
res = ch.find(channel)
if str(res) != "-1":
found=True
return found
def sendMsg(url):
attempts = 0
while True:
if attempts < 5:
try:
print(f"[+] Sending Message to Telegram ...")
resp = requests.post(url)
if resp.status_code == 200:
print(f"{colorSchemes.SUCCESS}[+] Message sent!\n")
break
elif resp.status_code != 200:
raise OSError
except OSError:
attempts += 1
print(f"{colorSchemes.FAILURE}[-] Sending failed!\n[+] Trying again ... (Attempt {attempts})")
continue
except KeyboardInterrupt:
print("\n[+] Please wait untill all messages in queue are sent!\n")
else:
print(f"{colorSchemes.FAILURE}[-] Message was not sent in 5 attempts. \n[-] Please check your network.")
break
if config.PROXY:
if config.AUTHENTICATION:
if config.USERNAME != None and config.PASSWORD != None:
socks.set_default_proxy(socks.SOCKS5, config.SOCKS5_SERVER, config.SOCKS5_PORT, username=config.USERNAME, password=config.PASSWORD)
print(f"\n[+] Proxy enabled with authentication set!\n[+] Proxy Server: {config.SOCKS5_SERVER}:{config.SOCKS5_PORT}")
else:
print(f"{colorSchemes.FAILURE}[-] Proxy authentication enabled but username/password not set.")
quit()
elif not config.AUTHENTICATION:
socks.set_default_proxy(socks.SOCKS5, config.SOCKS5_SERVER, config.SOCKS5_PORT)
print(f"{colorSchemes.WARNING}[+] Proxy enabled without authentication!\n[+] Proxy Server: {config.SOCKS5_SERVER}:{config.SOCKS5_PORT}")
socket.socket = socks.socksocket
print(f"{colorSchemes.WARNING}[+] Please wait for at least 30 seconds before first message.")
@bot.event
async def on_message(message):
try:
serverName = message.guild.name
serversList = config.serversList.keys()
channelName = message.channel.name
except AttributeError:
pass
print(f"Server: {serverName}, Channel: {channelName}")
if serverName in serversList:
channelsList = config.serversList[serverName]
if matchChannel(channelName, channelsList):
print(f"\n-------------------------------------------\n[+] Channel: {channelName}")
if message.content:
if message.mentions:
print(f"\n----------------\nUser Mentioned\n----------------")
message.content = replaceMentions(message.mentions, message.content, channel=False)
if message.channel_mentions:
print(f"\n----------------\nChannel Mentioned\n----------------")
message.content = replaceMentions(message.channel_mentions, message.content, channel=True)
toSend = f"{message.guild}/{message.channel}/{message.author.name}: {message.content}"
print(f"[+] Message: {toSend}")
toSend = removeTags(toSend)
url = f"{baseUrl}/sendMessage?text={toSend}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
if message.attachments:
attachmentUrl = message.attachments[0].url
if isPhoto(attachmentUrl):
url = f"{baseUrl}/sendPhoto?photo={attachmentUrl}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
elif isVideo(attachmentUrl):
url = f"{baseUrl}/sendVideo?video={attachmentUrl}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
elif isDoc(attachmentUrl):
url = f"{baseUrl}/sendDocument?document={attachmentUrl}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
if message.embeds:
embed = message.embeds[0].to_dict()
print(embed)
if str(embed['type']) == "rich":
if 'title' in embed.keys() and 'description' in embed.keys():
toSend = f"{message.guild}/{message.channel}/{message.author.name}: {embed['title']}\n{embed['description']}"
toSend = removeTags(toSend)
elif 'title' in embed.keys():
toSend = f"{message.guild}/{message.channel}/{message.author.name}: {embed['title']}"
toSend = removeTags(toSend)
elif 'description' in embed.keys():
toSend = f"{message.guild}/{message.channel}/{message.author.name}: {embed['description']}"
toSend = removeTags(toSend)
url = f"{baseUrl}/sendMessage?text={toSend}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
print(embed)
elif str(embed['type']) == "link":
toSend = f"{embed['title']}\n{embed['description']}\n{embed['url']}"
toSend = removeTags(toSend)
url = f"{baseUrl}/sendMessage?text={toSend}&chat_id={config.TELEGRAM_RECEIVER_CHAT_ID}"
sendMsg(url)
#Run the bot using the user token
try:
bot.run(config.USER_DISCORD_TOKEN)
except RuntimeError:
print("\n\nPlease Wait ...\nShutting down the bot ... \n")
quit()
except errors.HTTPException:
print(f"{colorSchemes.FAILURE}Invalid discord token or network down!")
quit()
except errors.LoginFailure:
print(f"{colorSchemes.FAILURE}Login failed to discord. May be bad token or network down!")
quit()
except clientExcps.ClientConnectionError:
print(f"{colorSchemes.FAILURE}[-] Proxy seems to be down or network problem.")
quit()