fork huge commit

This commit is contained in:
Your Name 2024-12-08 16:03:27 +03:00
parent aa4db3fc20
commit ed23de9ee5
4 changed files with 506 additions and 413 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
config.json
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
*.py[cod] *.py[cod]

View file

@ -1,3 +1,21 @@
This is fork from: https://github.com/S1S13AF7/ub4tg
Main changes:
* removed iris compatibility
* added loguru
* other some improvments
before start, create config.json file with this content:
```json
{
"api_id": 0000000,
"api_hash": "1234567890",
"timezone": "Europe/[Your_city]",
"db_pymysql": false,
"db_sqlite3": true,
"a_h": true
}
```
___
# ub4tg юзербот для телеграма. # ub4tg юзербот для телеграма.
покищо лише пінґ-понґ покищо лише пінґ-понґ
і збереження хто кого заразив і збереження хто кого заразив

View file

@ -1,6 +1,7 @@
# requirements.txt # requirements.txt
aiogram==2.19 aiohttp==3.9.0b0
aiogram
Telethon-Mod Telethon-Mod
#aiosqlite #aiosqlite
asyncio asyncio

897
ubot.py
View file

@ -1,412 +1,485 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#https://docs-python.ru/packages/telegram-klient-telethon-python/ <-info # https://docs-python.ru/packages/telegram-klient-telethon-python/ <-info
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
#from telethon.sync import TelegramClient # from telethon.sync import TelegramClient
from telethon import TelegramClient, events, utils from telethon import TelegramClient, events, utils
import os import sys
import re import json
import random import re
#import pytz import random
import time # import pytz
import time
import pymysql
import pymysql.cursors import pymysql
import pymysql.cursors
import sqlite3
import sqlite3
#Название сессии from loguru import logger
sessdb = 'tl-ub' logger.remove()
#Api ID и Api Hash полученные на my.telegram.org logger.level("DEBUG", color='<magenta>')
logger.add(sys.stderr, level="DEBUG")
api_id = 00000000
api_hash = 'blahblahblahblahblahblahblahblah' # Название сессии
timezone = "Europe/Kiev" sessdb = 'tl-ub'
with open("config.json", "r") as configfile:
db_pymysql = True#set True or False from types import SimpleNamespace
db_sqlite3 = True#set True or False cnf_dict = json.load(configfile)
config = SimpleNamespace(**cnf_dict)
async def main(): logger.debug('config loaded')
async with TelegramClient(sessdb,api_id,api_hash) as client:
client.parse_mode="HTML" # Api ID и Api Hash полученные на my.telegram.org
print('User-Bot started') api_id = config.api_id
me= await client.get_me() api_hash = config.api_hash
my_id = int(me.id) timezone = config.timezone
my_fn = me.first_name
print(my_id) db_pymysql = config.db_pymysql # set True or False
db_sqlite3 = config.db_sqlite3 # set True or False
if db_pymysql: a_h = config.a_h
con = pymysql.connect(host='localhost',
user='root',
password='V3rY$tR0NgPaS$Sw0Rd', @logger.catch
db='db', async def main():
charset='utf8mb4', async with TelegramClient(sessdb, api_id, api_hash) as client:
cursorclass=pymysql.cursors.DictCursor) client.parse_mode = "HTML"
d = con.cursor() logger.success('User-Bot started')
d.execute('''CREATE TABLE IF NOT EXISTS `tg_iris_zarazy` ( me = await client.get_me()
`when_int` int(11) unsigned NOT NULL DEFAULT '0', my_id = int(me.id)
`who_id` bigint(20) unsigned NOT NULL DEFAULT '0', my_fn = me.first_name
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0', logger.info(f'your id: {my_id}')
`u_link` varchar(500) NOT NULL DEFAULT '', # Changeble in run-time
`bio_str` varchar(11) NOT NULL DEFAULT '1', global auto_bioeb_sleep_interval, auto_bioeb_pathogen_threshold, auto_bioeb_min_interval, auto_bioeb_max_interval, auto_bioeb_stop
`bio_int` int(11) unsigned NOT NULL DEFAULT '1', auto_bioeb_sleep_interval = (6, 66) # the default on (re)start
`expr_int` int(11) unsigned NOT NULL DEFAULT '0', auto_bioeb_pathogen_threshold = 5 # these pathogens will be saved +- 1
`expr_str` varchar(11) NOT NULL DEFAULT '0', auto_bioeb_min_interval = (0.666, 3.666) # for fast leak pathogen
UNIQUE KEY `UNIQUE` (`who_id`,`user_id`) auto_bioeb_max_interval = (71, 121) # waiting for more pathogen
);'''); # Default strategy mean: you have 4-5 pathogens when auto bioeb is enabled, pathogen overflow reduced
con.commit() auto_bioeb_stop = False
d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_attack` (
`from_infect` int(11) unsigned NOT NULL DEFAULT '0', if db_pymysql:
`who_id` bigint(20) unsigned NOT NULL DEFAULT '0', con = pymysql.connect(host='localhost',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0', user='root',
`profit` int(11) unsigned NOT NULL DEFAULT '1', password='V3rY$tR0NgPaS$Sw0Rd',
`until_infect` int(11) unsigned NOT NULL DEFAULT '0', db='db',
`until_str` varchar(11) NOT NULL DEFAULT '0', charset='utf8mb4',
UNIQUE KEY `UNIQUE` (`who_id`,`user_id`) cursorclass=pymysql.cursors.DictCursor)
);'''); d = con.cursor()
con.commit() d.execute('''CREATE TABLE IF NOT EXISTS `tg_iris_zarazy` (
d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_users` ( `when_int` int(11) unsigned NOT NULL DEFAULT '0',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0', `who_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`when_int` int(11) unsigned NOT NULL DEFAULT '0', `user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`profit` int(11) unsigned NOT NULL DEFAULT '1', `u_link` varchar(500) NOT NULL DEFAULT '',
UNIQUE KEY `user_id` (`user_id`) `bio_str` varchar(11) NOT NULL DEFAULT '1',
);'''); `bio_int` int(11) unsigned NOT NULL DEFAULT '1',
con.commit() `expr_int` int(11) unsigned NOT NULL DEFAULT '0',
d.execute('''CREATE TABLE IF NOT EXISTS `tg_users_url` ( `expr_str` varchar(11) NOT NULL DEFAULT '0',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0', UNIQUE KEY `UNIQUE` (`who_id`,`user_id`)
`when_int` int(11) unsigned NOT NULL DEFAULT '0', );''')
`u_link` varchar(64) NOT NULL DEFAULT '', con.commit()
`f_name` text NOT NULL, d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_attack` (
PRIMARY KEY (`user_id`), `from_infect` int(11) unsigned NOT NULL DEFAULT '0',
UNIQUE KEY (`u_link`) `who_id` bigint(20) unsigned NOT NULL DEFAULT '0',
);'''); `user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
con.commit() `profit` int(11) unsigned NOT NULL DEFAULT '1',
`until_infect` int(11) unsigned NOT NULL DEFAULT '0',
if db_sqlite3: `until_str` varchar(11) NOT NULL DEFAULT '0',
conn = sqlite3.connect(f"{my_id}.sqlite")#покласти базу рядом? UNIQUE KEY `UNIQUE` (`who_id`,`user_id`)
#conn = sqlite3.connect(f"D:\\Misc\\projects\\Python\\ub4tg_db\\{my_id}.sqlite")#Або повністю );''')
c = conn.cursor() con.commit()
c.execute('''CREATE TABLE IF NOT EXISTS zarazy ( d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_users` (
user_id INTEGER NOT NULL DEFAULT 0 UNIQUE, `user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
when_int INTEGER NOT NULL DEFAULT 0, `when_int` int(11) unsigned NOT NULL DEFAULT '0',
bio_str VARCHAR NOT NULL DEFAULT 1, `profit` int(11) unsigned NOT NULL DEFAULT '1',
bio_int INTEGER NOT NULL DEFAULT 1, UNIQUE KEY `user_id` (`user_id`)
expr_int INTEGER NOT NULL DEFAULT 0, );''')
expr_str VARCHAR NOT NULL DEFAULT 0 con.commit()
)'''); d.execute('''CREATE TABLE IF NOT EXISTS `tg_users_url` (
conn.commit() `user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
c.execute('''CREATE TABLE IF NOT EXISTS avocado ( `when_int` int(11) unsigned NOT NULL DEFAULT '0',
user_id INTEGER NOT NULL DEFAULT 0 UNIQUE, `u_link` varchar(64) NOT NULL DEFAULT '',
when_int INTEGER NOT NULL DEFAULT 0, `f_name` text NOT NULL,
bio_str VARCHAR NOT NULL DEFAULT 1, PRIMARY KEY (`user_id`),
bio_int INTEGER NOT NULL DEFAULT 1, UNIQUE KEY (`u_link`)
expr_int INTEGER NOT NULL DEFAULT 0, );''')
expr_str VARCHAR NOT NULL DEFAULT 0 con.commit()
)''');
conn.commit() if db_sqlite3:
#################################################################### conn = sqlite3.connect(f"{my_id}.sqlite") # покласти базу рядом?
async def get_id(url): # conn = sqlite3.connect(f"D:\\Misc\\projects\\Python\\ub4tg_db\\{my_id}.sqlite")#Або повністю
user_id = 0 c = conn.cursor()
if "tg://openmessage?user_id=" in url: c.execute('''CREATE TABLE IF NOT EXISTS zarazy (
user_id = int(re.findall(r'user_id=([0-9]+)',url)[0]) user_id INTEGER NOT NULL DEFAULT 0 UNIQUE,
print(user_id) when_int INTEGER NOT NULL DEFAULT 0,
return user_id bio_str VARCHAR NOT NULL DEFAULT 1,
if "t.me/" in url: bio_int INTEGER NOT NULL DEFAULT 1,
if db_pymysql: expr_int INTEGER NOT NULL DEFAULT 0,
try: expr_str VARCHAR NOT NULL DEFAULT 0
d.execute("SELECT * FROM `tg_users_url` WHERE `u_link` = '%s' ORDER BY `when_int` DESC" % str(url)); )''')
user = d.fetchone(); conn.commit()
if user is None: c.execute('''CREATE TABLE IF NOT EXISTS avocado (
#print(f'не знайшли {url} у `tg_users_url`') user_id INTEGER NOT NULL DEFAULT 0 UNIQUE,
pass when_int INTEGER NOT NULL DEFAULT 0,
else: bio_str VARCHAR NOT NULL DEFAULT 1,
user_id = int(user['user_id']) bio_int INTEGER NOT NULL DEFAULT 1,
print(f'{url} in db: @{user_id}') expr_int INTEGER NOT NULL DEFAULT 0,
except Exception as Err: expr_str VARCHAR NOT NULL DEFAULT 0
print(f'E:{Err}/S {url} у `tg_users_url`') )''')
if user_id==0: conn.commit()
try: ####################################################################
d.execute("SELECT * FROM `tg_iris_zarazy` WHERE `u_link` = '%s' ORDER BY `when_int` DESC" % str(url));
user = d.fetchone(); async def get_id(url):
if user is None: user_id = 0
#print(f'не знайшли {url} у `tg_iris_zarazy`') if "tg://openmessage?user_id=" in url:
pass user_id = int(re.findall(r'user_id=([0-9]+)', url)[0])
else: logger.debug(user_id)
user_id = int(user['user_id']) return user_id
print(f'{url} in db: @{user_id}') if "t.me/" in url:
except Exception as Err: if db_pymysql:
print(f'E:{Err}/S {url} у `tg_iris_zarazy`') try:
if user_id==0: d.execute(
try: "SELECT * FROM `tg_users_url` WHERE `u_link` = '%s' ORDER BY `when_int` DESC" % str(url))
user_entity = await client.get_entity(url) user = d.fetchone()
if user_entity.id: if user is None:
user_id = int(user_entity.id) # print(f'не знайшли {url} у `tg_users_url`')
user_fn = user_entity.first_name or '' pass
print(f'ok:{url}/@{user_id}') else:
if db_pymysql: user_id = int(user['user_id'])
try: print(f'{url} in db: @{user_id}')
d.execute("INSERT INTO `tg_users_url` (`when_int`,`user_id`,`u_link`,`f_name`) VALUES (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE user_id = VALUES (user_id),u_link = VALUES (u_link),f_name = VALUES (f_name),when_int = VALUES (when_int);", (int(time.time()),int(user_id),str(url),str(user_fn))); con.commit() except Exception as Err:
except Exception as Err: print(f'E:{Err}/S {url} у `tg_users_url`')
print(f'E:{Err}') if user_id == 0:
except Exception as Err: try:
print(f'E:{Err}') user_entity = await client.get_entity(url)
#pass if user_entity.id:
return user_id user_id = int(user_entity.id)
user_fn = user_entity.first_name or ''
async def message_q( # спизжено print(f'ok:{url}/@{user_id}')
text: str, if db_pymysql:
user_id: int, try:
mark_read: bool = False, d.execute("INSERT INTO `tg_users_url` (`when_int`,`user_id`,`u_link`,`f_name`) VALUES (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE user_id = VALUES (user_id),u_link = VALUES (u_link),f_name = VALUES (f_name),when_int = VALUES (when_int);", (int(
delete: bool = False, time.time()), int(user_id), str(url), str(user_fn)))
): con.commit()
"""Отправляет сообщение и возращает ответ""" except Exception as Err:
async with client.conversation(user_id, exclusive=False) as conv: print(f'E:{Err}')
msg = await conv.send_message(text) except Exception as Err:
response = await conv.get_response() print(f'E:{Err}')
if mark_read: # pass
await conv.mark_read() return user_id
return response
async def message_q( # спизжено
#################################################################### text: str,
user_id: int,
mark_read: bool = False,
@client.on(events.NewMessage(outgoing=True,pattern='\.п')) delete: bool = False,
async def cmd_п(event): ):
mess = event.message """Отправляет сообщение и возращает ответ"""
text = mess.raw_text async with client.conversation(user_id, exclusive=False) as conv:
if text =='.п' or text=='.патоген': msg = await conv.send_message(text)
#FIX! А то спрацьовувало на .п(ередать,овысить,огладить,,,,,,,%) response = await conv.get_response()
l_r = await message_q( # отправляет сообщение боту и возвращает if mark_read:
f"/лаб в лс", await conv.mark_read()
5443619563, return response
mark_read=True,
delete=False, ####################################################################
)
h=utils.sanitize_parse_mode('html').unparse(l_r.message,l_r.entities) @client.on(events.NewMessage(pattern='.*йобнув.*|.*подверг(ла)? заражению.*|.*infected.*|.*сикди.*|.*насрал.*|.*подверг заморозке.*|.*за допомогою довіреності зазнала зараження.*|.*by authorization infected.*|.*при помощи анонимуса атаковала.*'))
lab_lines = h.splitlines() # текст с лабой, разбитый на строки @logger.catch
new = "" async def podverg_a(event):
if "🔬 Досье лаборатории" not in lab_lines[0]: logger.debug('New bio attack detected')
pass # хто там кого йобнув(ла)
else: m = event.message
t = m.raw_text
for i in lab_lines: # цикл for по всем строкам в тексте лабы bio_attack_themes = ( # I guess if too many themes it will be slow, but acceptable, because python slow as is.
if "🧪 Готовых патогенов:" in i: # UA theme
s = i.replace("🧪 Готовых патогенов:", "🧪 ") r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> йобнув.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
s = s.replace("из", "із") # RU theme
new+=f'{s}\n' # add \n r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> подверг.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
# EN theme
if "☣️ Био-опыт:" in i: r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> infected.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
s = i.replace("☣️ Био-опыт:", "☣️ ") # AZ theme
new+=f'{s}\n' # add \n r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> сикди.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
if "🧬 Био-ресурс:" in i: # "ПК гик" theme
s = i.replace("🧬 Био-ресурс:", "🧬 ") r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> насрал.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
new+=f'{s}\n' # add \n # "Новогодняя" theme
r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> подверг заморозке.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
if "❗️ Руководитель в состоянии горячки ещё" in i: # UA theme [via trust]
s = i.replace("❗️ Руководитель в состоянии горячки ещё", "🤬 ") r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> за допомогою довіреності зазнала зараження.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
new+=f'{s}\n' # add \n # EN theme [via trust]
if "вызванной болезнью" in i: r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> by authorization infected.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
# ❗️ Руководитель в состоянии горячки, вызванной болезнью «%s», ещё # idk what is theme [via trust]
#s = i.replace("❗️ Руководитель в состоянии горячки, вызванной болезнью ", "🤬 ") r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> при помощи анонимуса атаковала.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',
b = re.findall(r'вызванной болезнью «(.+)»',i)[0]#назва тої хєрні якою заразили )
s = i.replace(f"❗️ Руководитель в состоянии горячки, болезнью «{b}», ещё ", bio_expr_themes = (
f"🤬 <code>{b}</code>\n")#копіпабельно для пошуку # UA theme
await event.edit(new) #ред r"([0-9\.\,k]+) біо-ресурса",
# RU theme
r"Прибыль: ([0-9\.\,k]+)",
#################################################################### # EN theme
r"([0-9\.\,k]+) pcs\.",
# AZ theme
@client.on(events.NewMessage(pattern='.*подверг(ла)? заражению.*')) r"верир: ([0-9\.\,k]+)",
async def podverg(event): # "ПК гик" theme
#хто там кого подверг(ла) r"потеряет: ([0-9\.\,k]+)",
m = event.message # "Новогодняя" theme
t = m.raw_text r"Прибыль: ([0-9\.\,k]+)",
irises = [707693258,5137994780,5226378684,5443619563,5434504334] # UA theme [via trust]
if m.sender_id not in irises: r"([0-9\.\,k]+) біо-ресурса",
#print(f"@{m.sender_id} не Iris!?");#Або це або pass. що краще? # EN theme [via trust]
pass r"([0-9\.\,k]+) pcs\.",
elif len(m.entities) > 1: # idk what is theme [via trust]
h= utils.sanitize_parse_mode('html').unparse(t,m.entities)#HTML r'приносит: ([0-9\.\,k]+)',
r= re.findall(r'🦠 <a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> подверг.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',h) )
if r: default_infected_theme = r' на ([0-9\ ]+) д.*'
u1url=r[0][0] bio_infected_themes = (
u2url=r[0][1] # UA theme
u1id = await get_id(u1url) default_infected_theme,
u2id = await get_id(u2url) # RU theme
#print(f'{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}]')#показать default_infected_theme,
when=int(datetime.timestamp(m.date)) # EN theme
days=int(re.sub(r' ','',re.findall(r' на ([0-9\ ]+) д.*', t)[0])) r' for ([0-9\ ]+) d.*',
experience=re.findall(r"\+([0-9\.\,k]+) био-опыта", t)[0] # AZ theme
if ',' in experience: default_infected_theme,
experience=re.sub(r',', r'.',experience) # "ПК гик" theme
if 'k' in experience: default_infected_theme,
exp_int=int(float(re.sub('k', '',experience)) * 1000) # "Новогодняя" theme
else: default_infected_theme,
exp_int=int(experience) # UA theme [via trust]
if 'Объект ещё не подвергался заражению вашим патогеном' in event.raw_text: default_infected_theme,
exp_int=int(re.sub(r' ','',re.findall(r'по ([0-9\ ]+) ед.*',event.raw_text)[0])) # EN theme [via trust]
a=datetime.utcfromtimestamp(when)+timedelta(days=int(days), hours=3) default_infected_theme,
do_int=datetime.timestamp(a) # idk what is theme [via trust]
do_txt=str(a.strftime("%d.%m.%y")) default_infected_theme,
if u1id > 0 and u2id > 0 and u1id != u2id: )
if db_sqlite3 and u1id==my_id: default_pathogen_theme = r'Осталось: ([0-9\ ]+)'
try: bio_pathogen_theme = (
c.execute("INSERT INTO zarazy(user_id,when_int,bio_str,bio_int,expr_int,expr_str) VALUES (?, ?, ?, ?, ?, ?)", (int(u2id),int(when),str(experience),int(exp_int),int(datetime.timestamp(a)),str(a.strftime("%d.%m.%y")))); conn.commit() default_pathogen_theme,
except: default_pathogen_theme,
try: r'Remaining: ([0-9\ ]+)',
c.execute("UPDATE zarazy SET when_int = :wh, bio_str = :xp, bio_int = :xpi, expr_int = :end, expr_str = :do WHERE user_id = :z AND when_int <= :wh;", {"wh":int(when),"xp":str(experience),"xpi":int(exp_int),"end":int(datetime.timestamp(a)),"do":str(a.strftime("%d.%m.%y")),"z":int(u2id)}); conn.commit() default_pathogen_theme,
except Exception as Err: default_pathogen_theme,
print(f'err: {Err} zarazy') default_pathogen_theme,
if db_pymysql: default_pathogen_theme,
try: r'Remaining: ([0-9\ ]+)',
d.execute("INSERT INTO `tg_iris_zarazy` (`who_id`, `user_id`, `when_int`, `bio_str`, `bio_int`, `expr_int`, `expr_str`, `u_link`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE when_int=VALUES (when_int),bio_str=VALUES (bio_str),bio_int=VALUES (bio_int),expr_int=VALUES (expr_int),expr_str=VALUES (expr_str),u_link = VALUES (u_link);", (int(u1id),int(u2id),int(when),str(experience), int(exp_int), int(datetime.timestamp(a)),str(a.strftime("%d.%m.%y")),str(u2url))); con.commit() default_pathogen_theme,
print(f"\nINSERT INTO .... ON DUPLICATE KEY UPDATE # [@{u1id}] => [@{u2id}]\n") )
except Exception as Err:
print(f'err: {Err} /localhost') if m.sender_id != 6333102398:
#pass pass
print(f'''{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}] +{experience}''')#показать elif len(m.entities) > 1:
h = utils.sanitize_parse_mode(
'html').unparse(t, m.entities) # HTML
#################################################################### for theme in bio_attack_themes:
trying_theme_index = bio_attack_themes.index(theme)
logger.debug(f'trying theme {trying_theme_index}...')
@client.on(events.NewMessage(pattern='.*йобнув.*')) r = re.findall(theme, h)
async def podverg_a(event): if r:
#хто там кого йобнув(ла) logger.debug(f'found theme {trying_theme_index}')
m = event.message break
t = m.raw_text logger.debug(str(r))
if m.sender_id !=6333102398: if r:
pass u1url = r[0][0]
elif len(m.entities) > 1: u2url = r[0][1]
h= utils.sanitize_parse_mode('html').unparse(t,m.entities)#HTML u1id = await get_id(u1url)
r= re.findall(r'<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">.*</a> йобнув.+<a href="(tg://openmessage\?user_id=\d+|https://t\.me/\w+)">',h) u2id = await get_id(u2url)
if r: # print(f'{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}]')#показать
u1url=r[0][0] when = int(datetime.timestamp(m.date))
u2url=r[0][1] days = int(re.findall(bio_infected_themes[trying_theme_index], t)[0].replace(' ', ''))
u1id = await get_id(u1url) experience = re.findall(bio_expr_themes[trying_theme_index], t)[0].strip()
u2id = await get_id(u2url) if ',' in experience:
#print(f'{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}]')#показать experience = re.sub(r',', r'.', experience)
when=int(datetime.timestamp(m.date)) if 'k' in experience:
days=int(re.sub(r' ','',re.findall(r' на ([0-9\ ]+) д.*', t)[0])) exp_int = int(
experience=re.findall(r"([0-9\.\,k]+) біо-ресурса", t)[0] float(re.sub('k', '', experience)) * 1000)
if ',' in experience: else:
experience=re.sub(r',', r'.',experience) exp_int = int(experience)
if 'k' in experience: pathogen_remaining = int(re.findall(bio_pathogen_theme[trying_theme_index], t)[0])
exp_int=int(float(re.sub('k', '',experience)) * 1000) global auto_bioeb_sleep_interval, auto_bioeb_pathogen_threshold, auto_bioeb_min_interval, auto_bioeb_max_interval, auto_bioeb_stop
else: if pathogen_remaining <= auto_bioeb_pathogen_threshold and u1id == my_id:
exp_int=int(experience) auto_bioeb_sleep_interval = auto_bioeb_max_interval
a=datetime.utcfromtimestamp(when)+timedelta(days=int(days), hours=3) logger.warning(f'Interval bioeb changed (slow down): {auto_bioeb_sleep_interval}')
do_int=datetime.timestamp(a) elif u1id == my_id:
do_txt=str(a.strftime("%d.%m.%y")) auto_bioeb_sleep_interval = auto_bioeb_min_interval
if u1id > 0 and u2id > 0: logger.debug(f'Interval bioeb changed (more fast): {auto_bioeb_sleep_interval}')
if db_sqlite3 and u1id==my_id: a = datetime.utcfromtimestamp(
try: when)+timedelta(days=int(days), hours=3)
c.execute("INSERT INTO avocado(user_id,when_int,bio_str,bio_int,expr_int,expr_str) VALUES (?, ?, ?, ?, ?, ?)", (int(u2id),int(when),str(experience),int(exp_int),int(datetime.timestamp(a)),str(a.strftime("%d.%m.%y")))); conn.commit() do_int = datetime.timestamp(a)
except: do_txt = str(a.strftime("%d.%m.%y"))
try: if u1id > 0 and u2id > 0:
c.execute("UPDATE avocado SET when_int = :wh, bio_str = :xp, bio_int = :xpi, expr_int = :end, expr_str = :do WHERE user_id = :z AND when_int <= :wh;", {"wh":int(when),"xp":str(experience),"xpi":int(exp_int),"end":int(datetime.timestamp(a)),"do":str(a.strftime("%d.%m.%y")),"z":int(u2id)}); conn.commit() if db_sqlite3 and u1id == my_id:
except Exception as Err: try:
print(f'err: {Err} avocado') c.execute("INSERT INTO avocado(user_id,when_int,bio_str,bio_int,expr_int,expr_str) VALUES (?, ?, ?, ?, ?, ?)", (int(
if db_pymysql: u2id), int(when), str(experience), int(exp_int), int(datetime.timestamp(a)), str(a.strftime("%d.%m.%y"))))
try: conn.commit()
#from_infect who_id user_id profit until_infect until_str except:
d.execute("INSERT INTO `tg_bio_attack` (`who_id`, `user_id`, `from_infect`, `profit`, `until_infect`, `until_str`) VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE from_infect=VALUES (from_infect),profit=VALUES (profit),until_infect=VALUES (until_infect),until_str = VALUES (until_str);", (int(u1id),int(u2id),int(when),str(experience), int(datetime.timestamp(a)),str(a.strftime("%d.%m.%y")))); con.commit() try:
print(f"\nINSERT INTO .... ON DUPLICATE KEY UPDATE # [@{u1id}] => [@{u2id}]\n") c.execute("UPDATE avocado SET when_int = :wh, bio_str = :xp, bio_int = :xpi, expr_int = :end, expr_str = :do WHERE user_id = :z AND when_int <= :wh;", {
except Exception as Err: "wh": int(when), "xp": str(experience), "xpi": int(exp_int), "end": int(datetime.timestamp(a)), "do": str(a.strftime("%d.%m.%y")), "z": int(u2id)})
print(f'err: {Err} (tg_bio_attack)') conn.commit()
#pass except Exception as Err:
try: logger.exception(f'err: {Err} avocado')
#user_id when profit logger.debug('success writen my attack')
d.execute("INSERT INTO `tg_bio_users` (`user_id`, `when_int`, `profit`) VALUES (%s,%s,%s) ON DUPLICATE KEY UPDATE when_int=VALUES (when_int),profit=VALUES (profit);", (int(u2id),int(when),str(experience))); con.commit() if db_sqlite3 and u1id != my_id:
except Exception as Err: c.execute("INSERT OR REPLACE INTO avocado(user_id,when_int,bio_str,bio_int,expr_int) VALUES (?, ?, ?, ?, ?)", (int(
print(f'err: {Err} (tg_bio_users)') u2id), int(when), str(experience), int(exp_int), 0))
#pass conn.commit()
print(f'''{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}] +{experience}''')#показать logger.debug('success writen not my bio attack')
if db_pymysql:
try:
#################################################################### # from_infect who_id user_id profit until_infect until_str
d.execute("INSERT INTO `tg_bio_attack` (`who_id`, `user_id`, `from_infect`, `profit`, `until_infect`, `until_str`) VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE from_infect=VALUES (from_infect),profit=VALUES (profit),until_infect=VALUES (until_infect),until_str = VALUES (until_str);", (int(
u1id), int(u2id), int(when), str(experience), int(datetime.timestamp(a)), str(a.strftime("%d.%m.%y"))))
@client.on(events.NewMessage(outgoing=True, pattern='.biofuck')) con.commit()
async def cmd_bf(event): #крч акуратно з цим,вдруг шо я нічо print(
m = event.message f"\nINSERT INTO .... ON DUPLICATE KEY UPDATE # [@{u1id}] => [@{u2id}]\n")
when=int(datetime.timestamp(m.date)) except Exception as Err:
msg='🤷' # якщо нема кого то жри рандом. logger.exception(f'err: {Err} (tg_bio_attack)')
c.execute(f"SELECT * FROM `avocado` WHERE expr_int <= {when} ORDER BY expr_int,when_int ASC"); # pass
e_info=c.fetchall() try:
count = len(e_info) # user_id when profit
if count < 2: d.execute("INSERT INTO `tg_bio_users` (`user_id`, `when_int`, `profit`) VALUES (%s,%s,%s) ON DUPLICATE KEY UPDATE when_int=VALUES (when_int),profit=VALUES (profit);", (int(
nema=f'🤷 рандом хавай.' u2id), int(when), str(experience)))
await event.edit(nema) #ред con.commit()
print(nema) except Exception as Err:
else: logger.exception(f'err: {Err} (tg_bio_users)')
pong='✅ погнали...' # pass
await event.edit(pong) #ред if u1id == my_id:
print(f'є {count} потенційних пацієнтів. спробуєм їх сожрать') logger.success(
for row in e_info: f'''{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}] +{experience}, d: {days}''')
rs = float(random.uniform(6,96)) #скільки спим: random else:
eb = f'Биоеб {row[0]}' #повідомлення. logger.info(
m=await event.reply(eb) f'''{u1url} [@{u1id}] подверг(ла) {u2url} [@{u2id}] +{experience}, d: {days}''')
await asyncio.sleep(3.3)
await client.delete_messages(event.chat_id,m.id) ####################################################################
await asyncio.sleep(rs)
@client.on(events.NewMessage(outgoing=True, pattern=r'\.biofuck$'))
async def cmd_bf(event): # крч акуратно з цим,вдруг шо я нічо
#################################################################### m = event.message
when = int(datetime.timestamp(m.date))
msg = '🤷' # якщо нема кого то жри рандом.
@client.on(events.NewMessage(outgoing=True, pattern='.l2f')) c.execute(
async def cmd_l2f(event): #Local->file/{id}.sqlite f"SELECT * FROM `avocado` WHERE expr_int <= {when} ORDER BY expr_int,when_int ASC")
msg='для успішного виконання повинно бути обидві бази True' e_info = list(c.fetchall())
if db_pymysql: random.shuffle(e_info) # more random for random and reduce risk get very immun target after restart
try: count = len(e_info)
d.execute("SELECT * FROM `tg_iris_zarazy` WHERE who_id = %d ORDER BY when_int;" % int(my_id)); if count < 2:
bz_info = d.fetchall()#получить nema = '🤷 рандом хавай.'
count=len(bz_info) await event.edit(nema) # ред
if count==0: logger.warning(nema)
msg='🤷 інфа нема.' else:
print(msg) pong = '✅ погнали...'
else: global auto_bioeb_stop
saved=0 auto_bioeb_stop = False
for row in bz_info: await event.edit(pong) # ред
print(row) logger.info(f'є {count} потенційних пацієнтів. спробуєм їх сожрать')
id_user=int(row["user_id"]) for row in e_info:
bio_int=int(row["bio_int"]) if auto_bioeb_stop:
bio_str=str(row["bio_str"]) logger.warning('auto bioeb stopped')
when_int=int(row["when_int"]) await event.reply('stopped')
expr_int=int(row["expr_int"]) break
expr_str=str(re.sub(r'.20', r'.',row["expr_str"])) #.2024->.24 rs = float(random.uniform(auto_bioeb_sleep_interval[0], auto_bioeb_sleep_interval[1])) # скільки спим: random
user_url=str(f'tg://openmessage?user_id={id_user}') #fix для любителів мінять його eb = f'Биоеб {row[0]}' # повідомлення.
if db_sqlite3: m = await event.reply(eb)
try: await asyncio.sleep(3.3)
c.execute("INSERT INTO zarazy (user_id,when_int,bio_str,bio_int,expr_int,expr_str) VALUES (?, ?, ?, ?, ?, ?)", (int(id_user),int(when_int),str(bio_str),int(bio_int),int(expr_int),str(expr_str))); conn.commit() await client.delete_messages(event.chat_id, m.id)
saved+=1 logger.debug(f'bioeb sleep: {rs}s')
except: await asyncio.sleep(rs)
try:
c.execute("UPDATE zarazy SET when_int = :wh, bio_str = :xp, bio_int = :xpi, expr_int = :end, expr_str = :do WHERE user_id = :z AND when_int <= :wh;", {"wh":int(when_int),"xp":str(bio_str),"xpi":int(bio_int),"end":int(expr_int),"do":str(expr_str),"z":int(id_user)}); conn.commit() ####################################################################
except Exception as Err:
print(f'err: {Err} zarazy') @client.on(events.NewMessage(outgoing=True, pattern=r'\.biofuck stop$'))
msg=f"{saved} із {count}" async def stop_bioeb(event):
else: global auto_bioeb_stop
msg='для успішного виконання повинно бути обидві бази True' auto_bioeb_stop = True
except Exception as Err: await event.edit('Trying stop...') # ред
print(f'err: {Err} zarazy localhost')
msg=Err @client.on(events.NewMessage(pattern='🌡 У вас горячка вызванная'))
m=await event.reply(msg) async def need_h(event):
await asyncio.sleep(5) m = event.message
await client.delete_messages(event.chat_id, [event.id, m.id]) # reply = await client.get_messages(m.peer_id, ids=m.reply_to.reply_to_msg_id)
# logger.debug(reply)
if m.sender_id != 6333102398 and m.mentioned is False:
@client.on(events.NewMessage(outgoing=True, pattern='.ping')) pass
async def cmd_ping(event): elif a_h and m.mentioned:
# Say "pong!" whenever you send "!ping", then delete both messages # нада хил
m = await event.reply('pong!') ah = await message_q( # отправляет сообщение боту
await asyncio.sleep(5) "Хил",
await client.delete_messages(event.chat_id, [event.id, m.id]) 6333102398,
mark_read=True,
await client.run_until_disconnected() delete=False,
)
asyncio.run(main()) logger.debug(ah.text)
logger.warning('Used medkit')
elif m.mentioned:
# alternative method: just waiting, this reduce bio-res usage
global auto_bioeb_sleep_interval
auto_bioeb_sleep_interval = (3600, 3600)
logger.warning('Waiting for infection release... [For skip just bioeb somebody]')
####################################################################
@client.on(events.NewMessage(outgoing=True, pattern='.l2f'))
async def cmd_l2f(event): # Local->file/{id}.sqlite
msg = 'для успішного виконання повинно бути обидві бази True'
if db_pymysql:
try:
d.execute(
"SELECT * FROM `tg_iris_zarazy` WHERE who_id = %d ORDER BY when_int;" % int(my_id))
bz_info = d.fetchall() # получить
count = len(bz_info)
if count == 0:
msg = '🤷 інфа нема.'
print(msg)
else:
saved = 0
for row in bz_info:
print(row)
id_user = int(row["user_id"])
bio_int = int(row["bio_int"])
bio_str = str(row["bio_str"])
when_int = int(row["when_int"])
expr_int = int(row["expr_int"])
# .2024->.24
expr_str = str(
re.sub(r'.20', r'.', row["expr_str"]))
# fix для любителів мінять його
user_url = str(
f'tg://openmessage?user_id={id_user}')
if db_sqlite3:
try:
c.execute("INSERT INTO zarazy (user_id,when_int,bio_str,bio_int,expr_int,expr_str) VALUES (?, ?, ?, ?, ?, ?)", (int(
id_user), int(when_int), str(bio_str), int(bio_int), int(expr_int), str(expr_str)))
conn.commit()
saved += 1
except:
try:
c.execute("UPDATE zarazy SET when_int = :wh, bio_str = :xp, bio_int = :xpi, expr_int = :end, expr_str = :do WHERE user_id = :z AND when_int <= :wh;", {
"wh": int(when_int), "xp": str(bio_str), "xpi": int(bio_int), "end": int(expr_int), "do": str(expr_str), "z": int(id_user)})
conn.commit()
except Exception as Err:
print(f'err: {Err} zarazy')
msg = f"{saved} із {count}"
else:
msg = 'для успішного виконання повинно бути обидві бази True'
except Exception as Err:
logger.exception(f'err: {Err} zarazy localhost')
msg = Err
m = await event.reply(msg)
await asyncio.sleep(5)
await client.delete_messages(event.chat_id, [event.id, m.id])
@client.on(events.NewMessage(outgoing=True, pattern='.ping'))
async def cmd_ping(event):
# Say "pong!" whenever you send "!ping", then delete both messages
time_start = time.time()
m = await event.reply('pong!')
time_end = time.time()
delta = int(round((time_end - time_start) * 1000, 0))
await m.edit(f'pong message sending time: {delta} ms')
await asyncio.sleep(10)
await client.delete_messages(event.chat_id, [event.id, m.id])
await client.run_until_disconnected()
asyncio.run(main())