Skip to content

Commit 44a827c

Browse files
committed
refaq proxy on socks5
1 parent d92c1a8 commit 44a827c

File tree

4 files changed

+145
-146
lines changed

4 files changed

+145
-146
lines changed

coin_bot.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
from telethon import TelegramClient
99
from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
10+
from aiohttp_socks import ProxyType, ProxyConnector, ChainProxyConnector
11+
1012

1113
REG_CODE_TOKEN = r'data-code=\"(?P<code>[^\"]+)\".+token=\"(?P<token>[^\"]+)\"'
1214

@@ -16,9 +18,10 @@ def get_hash(text):
1618

1719

1820
class DialogLogic:
19-
def __init__(self, client, dialog):
21+
def __init__(self, client, dialog, proxy):
2022
self.client = client
2123
self.dialog = dialog
24+
self.proxy = proxy
2225

2326
async def send_msg(self, msg):
2427
await self.client.send_message(self.dialog.name, msg)
@@ -95,8 +98,8 @@ async def url_proceed(self, msg):
9598
url = msg.reply_markup.rows[0].buttons[0].url
9699

97100
print("Найдена ссылка:", url)
98-
99-
async with aiohttp.ClientSession() as session:
101+
connector = ProxyConnector.from_url(self.proxy.get_str())
102+
async with aiohttp.ClientSession(connector=connector) as session:
100103
text = ''
101104
try:
102105
resp = await session.get(url)
@@ -182,6 +185,7 @@ def __init__(self, api_id, api_hash, chat_names, phone, password):
182185
self.chat_names = chat_names
183186
self.phone = phone
184187
self.password = password
188+
self.proxy = None
185189
_hash = get_hash(f'{self.phone}_{self.password}')
186190

187191
if not os.path.isdir('./sessions'):
@@ -193,31 +197,36 @@ def __init__(self, api_id, api_hash, chat_names, phone, password):
193197
# proxy = (socks.SOCKS5, "5.133.197.203", 24382)
194198
self.client = None
195199

196-
def client_init(self, proxy):
197-
print(f'Started "{self.phone}" client')
198-
kwargs = {
199-
"phone": self.phone
200-
}
200+
async def client_init(self, proxy):
201+
print(f'Init "{self.phone}" client')
202+
203+
if self.client is not None and self.client.is_connected:
204+
await self.client.disconnect()
201205

206+
self.proxy = proxy
202207
self.client = TelegramClient(
203208
self.session,
204209
self.api_id,
205210
self.api_hash,
206-
proxy=proxy
207-
)
211+
proxy=self.proxy.get_tuple()
212+
)
213+
214+
kwargs = {
215+
"phone": self.phone
216+
}
208217

209218
if self.password is not None:
210219
kwargs['password'] = self.password
211220

212-
self.client.start(**kwargs)
221+
await self.client.start(**kwargs)
213222
print(f'Start client success')
214223

215224
async def get_dialogs(self):
216225
dialogs = []
217226
for dlg in await self.client.get_dialogs():
218227
if dlg.title in self.chat_names:
219228

220-
gl = DialogLogic(self.client, dlg)
229+
gl = DialogLogic(self.client, dlg, self.proxy)
221230
dialogs.append(gl)
222231

223232
return dialogs

main.py

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,35 @@
22
import argparse
33
import os
44
import json
5+
import linecache
6+
import sys
7+
import traceback
58

69
from coin_bot import CoinBot
7-
from proxy_manager import ProxyManager
10+
from proxy import ProxyManager
11+
from datetime import datetime
12+
from io import StringIO
13+
14+
15+
def traceback_msg(e):
16+
exc_type, exc_obj, first_tb = sys.exc_info()
17+
tb = StringIO()
18+
traceback.print_tb(first_tb, file=tb)
19+
sp_tab = ' '
20+
msg_ex = '''
21+
==========Exception===========
22+
Message:
23+
>>>
24+
{e}
25+
<<<
26+
Time: {time}
27+
Traceback:
28+
{tb}=============================='''.format(
29+
e=sp_tab + str(e).replace('\n', '\n' + sp_tab),
30+
time=datetime.now(),
31+
tb=tb.getvalue()
32+
)
33+
return msg_ex
834

935

1036
async def wait_exit():
@@ -41,22 +67,25 @@ async def main():
4167
for cfg in config_data['clients']
4268
]
4369

44-
proxy_manager = ProxyManager('https://api.telegram.org')
70+
proxy_manager = ProxyManager()
4571

4672
while True:
47-
tasks = []
73+
run_tasks = []
74+
75+
await proxy_manager.load_proxys()
4876

77+
print('run init bots')
4978
for bot in bots:
50-
bot.client_init(
51-
await proxy_manager.get_next_proxy()
52-
)
53-
tasks.append(bot.run())
79+
proxy = await proxy_manager.get_proxy('https://api.telegram.org')
80+
await bot.client_init(proxy)
81+
run_tasks.append(bot.run())
5482

5583
try:
5684
# runing all bots
57-
await asyncio.gather(*tasks)
85+
print('run all bots')
86+
await asyncio.gather(*run_tasks)
5887
except Exception as e:
59-
print('Exception:', e)
88+
print(traceback_msg(e))
6089

6190
await asyncio.sleep(60)
6291

@@ -65,4 +94,5 @@ async def main():
6594
# runing main
6695
loop = asyncio.get_event_loop()
6796
loop.create_task(wait_exit())
68-
loop.run_until_complete(main())
97+
loop.create_task(main())
98+
loop.run_forever()

proxy.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
2+
import aiohttp
3+
import asyncio
4+
import json
5+
import socks
6+
import re
7+
8+
from aiohttp_socks import ProxyType, ProxyConnector, ChainProxyConnector
9+
10+
11+
class ProxyObject:
12+
def __init__(self, ip, port):
13+
self.ip = ip
14+
self.port = int(port)
15+
16+
def get_tuple(self):
17+
return socks.SOCKS5, self.ip, self.port
18+
19+
def get_str(self):
20+
return f'socks5://{self.ip}:{self.port}'
21+
22+
def __str__(self):
23+
return f'{self.ip}:{self.port}'
24+
25+
async def check_url(self, url):
26+
try:
27+
connector = ProxyConnector.from_url(self.get_str())
28+
async with aiohttp.ClientSession(connector=connector) as _sess:
29+
response = await _sess.get(url, timeout=2)
30+
if response.status == 200:
31+
return True
32+
except Exception as e:
33+
# print("ER:", type(e), e)
34+
pass
35+
36+
return False
37+
38+
39+
class ProxyManager:
40+
def __init__(self):
41+
self.biffer_proxys = []
42+
self.proxys = []
43+
44+
async def load_proxys(self):
45+
print("run load proxy")
46+
47+
url = 'https://api.proxyscrape.com/?request=share&proxytype=socks5&timeout=1000&country=all'
48+
async with aiohttp.ClientSession() as _sess:
49+
response = await _sess.get(url)
50+
if response.status != 200:
51+
raise Exception(f'Failed request to "{url}" url')
52+
53+
url = str(response.url).replace(
54+
'https://textitor.com/',
55+
'https://api.textitor.com/'
56+
) + '/plain'
57+
58+
response = await _sess.get(url)
59+
if response.status != 200:
60+
raise Exception(f'Failed request to "{url}" url')
61+
62+
text = await response.text()
63+
x = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,6}', text)
64+
65+
pxs = [x.split(':') for x in text.split('\n')]
66+
self.biffer_proxys = [ProxyObject(x[0], x[1]) for x in pxs if len(x) == 2]
67+
print(f'load {len(self.proxys)} proxys')
68+
69+
async def get_proxy(self, test_url):
70+
print('getting proxy')
71+
count_try = 0
72+
while count_try < 10:
73+
if len(self.proxys) == 0:
74+
await self.load_proxys()
75+
76+
proxy = self.proxys.pop()
77+
78+
if await proxy.check_url(test_url):
79+
print(f"Proxy {proxy} find success")
80+
return proxy
81+
82+
await asyncio.sleep(1)
83+
84+
raise Exception("Max count trys getting proxy =(")

proxy_manager.py

Lines changed: 0 additions & 124 deletions
This file was deleted.

0 commit comments

Comments
 (0)