# -*- coding: utf-8 -*- from s import is_termux, sessdb, default_directory, config, states from src import autobioebbing, avocmine, victimsbackup, updatenotif # from telethon.sync import TelegramClient # https://docs-python.ru/packages/telegram-klient-telethon-python/ <-info from telethon import TelegramClient, events from loguru import logger import time import sys import asyncio import re import pymysql import pymysql.cursors import sqlite3 logger.remove() logger.level("DEBUG", color='') logger.add(sys.stderr, level="DEBUG") @logger.catch async def main(): async with TelegramClient(sessdb, config.api_id, config.api_hash, connection_retries=300, request_retries=10,) as client: 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: 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`) );''') 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`) );''') 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`) );''') 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`) );''') con.commit() if config.db_sqlite3: logger.debug('sqlite3 database connecting...') if is_termux: conn = sqlite3.connect(f"{default_directory}/{my_id}.sqlite") else: conn = sqlite3.connect(f"{my_id}.sqlite") # покласти базу рядом 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 conn.commit() c.execute('''CREATE TABLE IF NOT EXISTS avocado_exclude ( user_id INTEGER NOT NULL DEFAULT 0 UNIQUE, reason VARCHAR )''') conn.commit() 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') #################################################################### 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: 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}') except: pass 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: 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()) await victimsbackup.bio_backup_stealing(client, c, conn, default_directory) if config.db_pymysql: await autobioebbing.eb(client, c, conn, con, d, get_id, my_id, message_q) else: await autobioebbing.eb(client, c, conn, None, None, get_id, my_id, message_q) asyncio.ensure_future(avocmine.automine_avocado_task(client)) @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() msg = "Session stats:\n" \ f"Medkit usage: {states.stats_medkit}\n" \ f"Most common chats:\n" \ f"{stats_most_chats}".replace(',', '\n') await event.edit(msg) @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() if __name__ == '__main__': asyncio.run(main())