ub4tg/ubot.py

209 lines
9.2 KiB
Python
Raw Normal View History

2024-12-08 15:03:27 +02:00
# -*- coding: utf-8 -*-
from s import is_termux, sessdb, default_directory, config, states
from src import autobioebbing, avocmine, victimsbackup, updatenotif
2024-12-08 15:03:27 +02:00
# from telethon.sync import TelegramClient
2024-12-18 19:27:16 +02:00
# https://docs-python.ru/packages/telegram-klient-telethon-python/ <-info
from telethon import TelegramClient, events
2024-12-18 19:27:16 +02:00
from loguru import logger
2024-12-08 15:03:27 +02:00
2024-12-18 19:27:16 +02:00
import time
2024-12-08 15:03:27 +02:00
import sys
2024-12-21 07:45:41 +02:00
import os
2024-12-18 19:27:16 +02:00
import asyncio
2024-12-08 15:03:27 +02:00
import re
import pymysql
import pymysql.cursors
import sqlite3
2024-12-18 19:27:16 +02:00
2024-12-08 15:03:27 +02:00
logger.remove()
logger.level("DEBUG", color='<magenta>')
logger.add(sys.stderr, level="DEBUG")
2024-12-09 08:53:35 +02:00
2024-12-08 15:03:27 +02:00
@logger.catch
async def main():
async with TelegramClient(sessdb, config.api_id, config.api_hash, connection_retries=300, request_retries=10,) as client:
2024-12-08 15:03:27 +02:00
client.parse_mode = "HTML"
logger.success('User-Bot started')
me = await client.get_me()
my_id = int(me.id)
my_fn = me.first_name
logger.info(f'your id: {my_id}')
if config.db_pymysql:
2024-12-08 15:03:27 +02:00
con = pymysql.connect(host='localhost',
user='root',
password='V3rY$tR0NgPaS$Sw0Rd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
d = con.cursor()
d.execute('''CREATE TABLE IF NOT EXISTS `tg_iris_zarazy` (
`when_int` int(11) unsigned NOT NULL DEFAULT '0',
`who_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`u_link` varchar(500) NOT NULL DEFAULT '',
`bio_str` varchar(11) NOT NULL DEFAULT '1',
`bio_int` int(11) unsigned NOT NULL DEFAULT '1',
`expr_int` int(11) unsigned NOT NULL DEFAULT '0',
`expr_str` varchar(11) NOT NULL DEFAULT '0',
UNIQUE KEY `UNIQUE` (`who_id`,`user_id`)
);''')
2024-12-08 15:03:27 +02:00
con.commit()
d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_attack` (
`from_infect` int(11) unsigned NOT NULL DEFAULT '0',
`who_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`profit` int(11) unsigned NOT NULL DEFAULT '1',
`until_infect` int(11) unsigned NOT NULL DEFAULT '0',
`until_str` varchar(11) NOT NULL DEFAULT '0',
UNIQUE KEY `UNIQUE` (`who_id`,`user_id`)
);''')
2024-12-08 15:03:27 +02:00
con.commit()
d.execute('''CREATE TABLE IF NOT EXISTS `tg_bio_users` (
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`when_int` int(11) unsigned NOT NULL DEFAULT '0',
`profit` int(11) unsigned NOT NULL DEFAULT '1',
UNIQUE KEY `user_id` (`user_id`)
);''')
2024-12-08 15:03:27 +02:00
con.commit()
d.execute('''CREATE TABLE IF NOT EXISTS `tg_users_url` (
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`when_int` int(11) unsigned NOT NULL DEFAULT '0',
`u_link` varchar(64) NOT NULL DEFAULT '',
`f_name` text NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY (`u_link`)
);''')
2024-12-08 15:03:27 +02:00
con.commit()
if config.db_sqlite3:
2024-12-13 16:50:03 +02:00
logger.debug('sqlite3 database connecting...')
if is_termux:
conn = sqlite3.connect(f"{default_directory}/{my_id}.sqlite")
else:
2024-12-18 20:45:33 +02:00
# покласти базу рядом
conn = sqlite3.connect(f"{my_id}.sqlite")
2024-12-08 15:03:27 +02:00
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS avocado (
user_id INTEGER NOT NULL DEFAULT 0 UNIQUE,
when_int INTEGER NOT NULL DEFAULT 0,
bio_int INTEGER NOT NULL DEFAULT 1,
expr_int INTEGER NOT NULL DEFAULT 0,
expr_str VARCHAR NOT NULL DEFAULT 0
)''')
try:
c.execute('ALTER TABLE avocado DROP COLUMN bio_str')
logger.warning('bio_str in database no more used, deleted!')
except:
pass
2024-12-08 15:03:27 +02:00
conn.commit()
2024-12-13 00:00:16 +02:00
c.execute('''CREATE TABLE IF NOT EXISTS avocado_exclude (
user_id INTEGER NOT NULL DEFAULT 0 UNIQUE,
reason VARCHAR
)''')
conn.commit()
2024-12-13 16:50:03 +02:00
logger.debug('sqlite3 database initialized')
logger.debug('optimizing database...')
c.execute('PRAGMA optimize')
c.execute('PRAGMA journal_mode = WAL')
c.execute('PRAGMA synchronous = normal')
c.execute('VACUUM')
logger.debug('optimized')
2024-12-13 00:00:16 +02:00
2024-12-08 15:03:27 +02:00
####################################################################
async def get_id(url):
user_id = 0
if "tg://openmessage?user_id=" in url:
user_id = int(re.findall(r'user_id=([0-9]+)', url)[0])
logger.debug(user_id)
return user_id
if "t.me/" in url:
if config.db_pymysql:
2024-12-08 15:03:27 +02:00
try:
d.execute(
"SELECT * FROM `tg_users_url` WHERE `u_link` = '%s' ORDER BY `when_int` DESC" % str(url))
user = d.fetchone()
if user is None:
pass
else:
user_id = int(user['user_id'])
print(f'{url} in db: @{user_id}')
2024-12-14 18:32:12 +02:00
except:
pass
2024-12-08 15:03:27 +02:00
if user_id == 0:
try:
user_entity = await client.get_entity(url)
if user_entity.id:
user_id = int(user_entity.id)
user_fn = user_entity.first_name or ''
print(f'ok:{url}/@{user_id}')
if config.db_pymysql:
2024-12-08 15:03:27 +02:00
try:
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:
print(f'E:{Err}')
except Exception as Err:
print(f'E:{Err}')
# pass
return user_id
async def message_q( # спизжено
text: str,
user_id: int,
mark_read: bool = False,
delete: bool = False,
):
"""Отправляет сообщение и возращает ответ"""
async with client.conversation(user_id, exclusive=False) as conv:
msg = await conv.send_message(text)
response = await conv.get_response()
if mark_read:
await conv.mark_read()
return response
####################################################################
if is_termux:
asyncio.ensure_future(updatenotif.git_notifications_update())
2024-12-21 07:45:41 +02:00
elif os.name == 'posix':
print(f'\33]0;bot {my_id}\a', end='', flush=True)
await victimsbackup.bio_backup_stealing(client, c, conn, default_directory)
if config.db_pymysql:
2024-12-18 19:27:16 +02:00
await autobioebbing.eb(client, c, conn, con, d, get_id, my_id, message_q)
else:
2024-12-18 19:27:16 +02:00
await autobioebbing.eb(client, c, conn, None, None, get_id, my_id, message_q)
asyncio.ensure_future(avocmine.automine_avocado_task(client))
2024-12-08 15:03:27 +02:00
2024-12-09 07:14:32 +02:00
@client.on(events.NewMessage(outgoing=True, pattern=r'\.bstat$'))
async def bio_stat(event):
stats_most_chats = states.states.stats_most_infect_spam_chats.most_common()
2024-12-09 07:14:32 +02:00
msg = "Session stats:\n" \
2024-12-09 20:47:56 +02:00
f"Medkit usage: {states.stats_medkit}\n" \
f"Most common chats:\n" \
f"{stats_most_chats}".replace(',', '\n')
2024-12-09 08:05:41 +02:00
await event.edit(msg)
2024-12-08 15:03:27 +02:00
@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()
2024-12-18 00:15:40 +02:00
if __name__ == '__main__':
asyncio.run(main())