Skip to content

Commit

Permalink
Merge pull request #188 from AirportR/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
AirportR authored Apr 28, 2024
2 parents b4a1fe7 + 06eabfb commit 1a18d20
Show file tree
Hide file tree
Showing 16 changed files with 190 additions and 238 deletions.
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,10 @@ pip install -r requirements.txt
```
### 为bot进行相关配置
以下为启动bot的最低要求(如果您是新手,建议先以最低要求把bot跑起来,否则自己乱改配置容易出现不可预知的错误。)
- 管理员配置

新建一个名为config.yaml的文件,放在./resources下,项目有模板例子名为./resources/config.yaml.example,在config.yaml中写入如下信息:

新建一个名为config.yaml的文件,放在./resources下,项目有模板例子名为./resources/config.yaml.example,在config.yaml中写入如下信息:

```yaml
admin:
- 12345678 # 改成自己的telegram uid
- 8765431 # 这是第二行,表示第二个管理员,没有第二个管理员就把该行删除。
```


- bot相关配置
```yaml
Expand All @@ -155,6 +150,14 @@ pip install -r requirements.txt
path: "./bin/FullTCore" #这里改成代理客户端文件路径
```
Windows系统名字后缀名.exe要加上,其他类Unix系统不需要加后缀名。
- 管理员配置(可选)
从3.6.10版本开始,bot在首次启动时会将接收到的第一条消息的发送者作为管理员,一般无需手动配置,除非您想设置多个管理员:
```yaml
admin:
- 12345678 # 改成自己的telegram uid
- 8765431 # 这是第二行,表示第二个管理员,没有第二个管理员就把该行删除。
```
- HTTP代理配置(可选)
如果是在中国大陆地区使用,可能部分网址无法直接连接。可在config.yaml中写入如下信息,下载资源文件时将自动应用该项配置:
Expand Down
14 changes: 5 additions & 9 deletions addons/builtin/copilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
try:
from utils import retry
except ImportError:
def retry(time=3):
def retry(_=3):
def wrapper(func):
async def inner(*args, **kwargs):
await func(*args, **kwargs)
Expand All @@ -31,7 +31,7 @@ async def fetch_copilot(collector, session: aiohttp.ClientSession, proxy=None):
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'
}
url = 'https://www.bing.com/search?q=bing&showconv=1'
url = 'https://www.bing.com/search?q=bing'
async with session.get(url, headers=headers, proxy=proxy, timeout=5) as resp:
if resp.history:
for i in resp.history:
Expand All @@ -40,8 +40,8 @@ async def fetch_copilot(collector, session: aiohttp.ClientSession, proxy=None):
return True
if resp.status == 200:
text = await resp.text()
index = text.find("Copilot")
# print(index)
# index = text.find("Copilot")
index = text.find("b-scopeListItem-conv")
try:
region = re.search(r'Region:"(\w\w)"', text).group(1)
# region2 = re.search(r'Region:"(.*)"', text).group(1)
Expand All @@ -52,12 +52,8 @@ async def fetch_copilot(collector, session: aiohttp.ClientSession, proxy=None):
if region == "WW":
region = ""
region = region.upper()
collector.info['copilot'] = "失败" + region if index < 80000 or region in UNS_REGION else '解锁' + region
collector.info['copilot'] = "失败" + region if index == -1 or region in UNS_REGION else '解锁' + region
return True

# with open("temp", "w", encoding="utf-8") as fp:
# fp.write(text)
# print(text)
return True


Expand Down
17 changes: 9 additions & 8 deletions addons/builtin/ssh22.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import socks
import aiohttp
from loguru import logger

from aiohttp_socks import ProxyConnector
from utils import retry

SUC_LIST = []
Expand Down Expand Up @@ -40,19 +40,19 @@ async def fetch_ssh(collector, session: aiohttp.ClientSession, proxy: str = None
conn = session.connector

try:
if type(conn).__name__ == 'ProxyConnector':
if type(conn) is ProxyConnector:
paddr = conn._proxy_host
pport = conn._proxy_port
else:
parsed = proxy.lstrip("http://").rstrip("/").split(":")
parsed = proxy.removeprefix("http://").removesuffix("/").split(":")
paddr = parsed[0]
pport = int(parsed[1])
mysocket = socks.socksocket(type=socket.SOCK_STREAM)
mysocket.set_proxy(socks.PROXY_TYPE_SOCKS5, addr=paddr, port=pport)

async def check():
mysocket = socks.socksocket(type=socket.SOCK_STREAM)
mysocket.set_proxy(socks.PROXY_TYPE_SOCKS5, addr=paddr, port=pport)
mysocket.settimeout(10)

mysocket.settimeout(10)
async def check():

async with async_timeout.timeout(10):
mysocket.connect((_host, _sport))
Expand All @@ -73,7 +73,8 @@ async def check():
res = await check()
except (TimeoutError, OSError):
return False
# res = await asyncio.get_running_loop().run_in_executor(None, check)
finally:
mysocket.close()
if res is True:
SUC_LIST.append(ip)

Expand Down
75 changes: 40 additions & 35 deletions addons/builtin/tiktok.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,41 @@
import asyncio

import aiohttp
from aiohttp import ClientConnectorError
import async_timeout
from loguru import logger

from utils import retry


# collector section
@retry(2)
@retry(1)
async def fetch_tiktok(collector, session: aiohttp.ClientSession, proxy=None):
"""
tiktok解锁测试,检查测速是否被ban
tiktok解锁测试
:param collector:
:param session:
:param proxy:
:return:
"""
tiktokurl = 'https://www.tiktok.com'
try:
# async with aiohttp.ClientSession() as session:
async with session.get(tiktokurl, proxy=proxy, timeout=5) as resq:
if resq.status == 200:
response_text = await resq.text()
region = response_text.find('"region":')
if region != -1:
region = response_text[region:].split('"')[3]
# print("Tiktok Region: ", region)
collector.info['tiktok'] = f"解锁({region})"
conn = session.connector
if type(conn).__name__ == 'ProxyConnector':
proxy = "http://" + conn._proxy_host + ":" + str(conn._proxy_port)
async with async_timeout.timeout(10):
async with aiohttp.ClientSession() as session:
async with session.get(tiktokurl, proxy=proxy, timeout=5) as resp:
if resp.status == 200:
response_text = await resp.text()
region = response_text.find('"region":')
if region != -1:
region = response_text[region:].split('"')[3]
# print("Tiktok Region: ", region)
collector.info['tiktok'] = f"解锁({region})"
else:
# print("Tiktok Region: Not found")
collector.info['tiktok'] = "失败"
else:
# print("Tiktok Region: Not found")
collector.info['tiktok'] = "失败"
else:
collector.info['tiktok'] = "未知"
return True
except ClientConnectorError as c:
logger.warning("tiktok请求发生错误:" + str(c))
await fetch_tiktok(collector, session=session, proxy=proxy)
collector.info['tiktok'] = "连接错误"
return False
except asyncio.exceptions.TimeoutError:
await fetch_tiktok(collector, session=session, proxy=proxy)
collector.info['tiktok'] = "超时"
return False
collector.info['tiktok'] = "未知"
return True


def task(Collector, session, proxy):
Expand All @@ -57,8 +50,10 @@ def get_tiktok_info(ReCleaner):
"""
try:
if 'tiktok' not in ReCleaner.data:
logger.warning("采集器内无数据")
return "N/A"
else:
# logger.info("tiktok解锁:" + str(ReCleaner.data.get('tiktok', "N/A")))
return ReCleaner.data.get('tiktok', "N/A")
except Exception as e:
logger.error(e)
Expand All @@ -71,13 +66,23 @@ def get_tiktok_info(ReCleaner):
"GET": get_tiktok_info
}

if __name__ == "__main__":
async def demo():
class FakeColl:
def __init__(self):
self.info = {}
self.data = self.info

async def demo():
from utils import script_demo
await script_demo(fetch_tiktok, proxy='http://127.0.0.1:11112')
fakecl = FakeColl()
from aiohttp_socks import ProxyConnector
conn = ProxyConnector(host="127.0.0.1", port=11112, limit=0)
session = aiohttp.ClientSession(connector=conn)
await fetch_tiktok(fakecl, session, proxy=None)
print(fakecl.info)
await session.close()


if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(demo())
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(demo())
39 changes: 39 additions & 0 deletions utils/bot.py → botmodule/bot.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

from pyrogram import Client, filters
from pyrogram.types import CallbackQuery, Message
from loguru import logger
Expand All @@ -22,6 +24,7 @@


def loader(app: Client):
born(app)
command_loader(app)
command_loader2(app)
callback_loader(app)
Expand Down Expand Up @@ -78,6 +81,42 @@ async def _(_: Client, __: Message):
break_speed.append(True)


def born(app: "Client"):
if not bool(admin):
from pyrogram.handlers import MessageHandler
# 如果admin列表为空,说明没有配置管理员或者初次启动,第一个给bot发私聊消息的将是管理员。
# 这是来自小说的灵感,蛋生生物睁开第一眼看到的第一个目标是它的母亲。
logger.warning("您尚未配置管理员,请在bot启动成功后私聊bot发送任意消息,bot会自动将您注册为管理员。")
lock = asyncio.Lock()

async def waiting_born(client: "Client", message: "Message"):
async with lock:
admin_id = message.from_user.id
await message.reply(f"✅初始化成功,您已被确定成管理员,已将您的身份写入到配置文件~\n"
f"您的UID为: {admin_id}\n"
f"用户名: {message.from_user.username}")
# 管理员身份添加到配置文件
if admin_id:
config.add_admin(message.from_user.id)
config.reload()
# 删除此handler回调,否则会将所有人注册成管理员
if -100 in app.dispatcher.groups:
_g: list = app.dispatcher.groups[-100]
self_h = None
for _h in _g:
if isinstance(_h, MessageHandler) and "waiting_born" == _h.callback.__name__:
self_h = _h
break
if self_h is not None:
app.remove_handler(self_h, -100)
logger.info(f"✅已初始化管理员, UID: {admin_id}Username:{message.from_user.username},正在重启bot...")
await botmodule.restart_or_killme(client, message)
hl = MessageHandler(waiting_born, filters.private)
app.add_handler(hl, -100)
else:
return


def command_loader(app: Client):
task_list = ["test", "testurl", "analyze", "topo", "analyzeurl", "topourl", "speed", "speedurl", "invite"]

Expand Down
Loading

0 comments on commit 1a18d20

Please sign in to comment.