Version 1.0 pushed

This commit is contained in:
Mattia 2020-06-05 14:53:21 +02:00 committed by GitHub
parent 29d7350e6c
commit 4aafdbb71e
15 changed files with 861 additions and 0 deletions

1
BotBase/__init__.py Normal file
View File

@ -0,0 +1 @@
__version__ = (1, 0, 0)

View File

@ -0,0 +1 @@
__version__ = (1, 0, 0)

145
BotBase/database/query.py Normal file
View File

@ -0,0 +1,145 @@
import sqlite3.dbapi2 as sqlite3
from ..config import DB_GET_USERS, DB_GET_USER, DB_RELPATH, DB_SET_USER, DB_GET_IMEI, DB_SET_IMEI, DB_GET_API_DATE, \
DB_SET_API_DATE, DB_SET_IMEI_DATA, DB_GET_IMEI_DATA
import logging
import time
from types import FunctionType
def get_user(tg_id: int):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
query = cursor.execute(DB_GET_USER, (tg_id,))
return query.fetchone()
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_USER query: {query_error}")
def get_users():
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
query = cursor.execute(DB_GET_USERS)
return query.fetchall()
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_USERS query: {query_error}")
def set_user(tg_id: int, uname: str):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
cursor.execute(DB_SET_USER, (None, tg_id, uname, time.strftime("%d/%m/%Y %T %p")))
cursor.close()
return True
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_USERS query: {query_error}")
def set_imei(tg_id: int, imei: str):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
cursor.execute(DB_SET_IMEI, (imei, tg_id))
cursor.close()
return True
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_SET_IMEI query: {query_error}")
def get_imei(tg_id: int):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
query = cursor.execute(DB_GET_IMEI, (tg_id,))
return query.fetchone()
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_IMEI query: {query_error}")
def set_api_date(tg_id: int, timer: FunctionType = time.time):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
cursor.execute(DB_SET_API_DATE, (int(timer()), tg_id))
cursor.close()
return True
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_SET_API_DATE query: {query_error}")
def get_api_date(tg_id: int):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
query = cursor.execute(DB_GET_API_DATE, (tg_id,))
return query.fetchone()
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_API_DATE query: {query_error}")
def set_imei_data(imei: int, json_data: str):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
cursor.execute(DB_SET_IMEI_DATA, (imei, json_data))
cursor.close()
return True
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_SET_IMEI_DATA query: {query_error}")
def get_imei_data(imei: int):
try:
database = sqlite3.connect(DB_RELPATH)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
query = cursor.execute(DB_GET_IMEI_DATA, (imei,))
return query.fetchone()
except sqlite3.Error as query_error:
logging.error(f"An error has occurred while executing DB_GET_IMEI_DATA query: {query_error}")

View File

@ -0,0 +1 @@
__version__ = (1, 0, 0)

View File

@ -0,0 +1,44 @@
from pyrogram.errors import RPCError, FloodWait
import time
import logging
def edit_message_text(update, *args, **kwargs):
"""Edits a message in a way that never triggers exceptions and logs errors"""
try:
return update.edit_message_text(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def edit_message_caption(update, *args, **kwargs):
"""Edits a message caption in a way that never triggers exceptions and logs errors"""
try:
return update.edit_message_caption(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def edit_message_media(update, *args, **kwargs):
"""Edits a message media in a way that never triggers exceptions and logs errors"""
try:
return update.edit_message_media(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False

View File

@ -0,0 +1,72 @@
from pyrogram.errors import RPCError, FloodWait
from pyrogram import Client
import time
import logging
def send_message(client: Client, *args, **kwargs):
"""Sends a message in a way that never triggers exceptions and logs errors"""
try:
return client.send_message(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def send_photo(client: Client, *args, **kwargs):
"""Sends a photo in a way that never triggers exceptions and logs errors"""
try:
return client.send_photo(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def send_audio(client: Client, *args, **kwargs):
"""Sends an audio in a way that never triggers exceptions and logs errors"""
try:
return client.send_audio(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def send_sticker(client: Client, *args, **kwargs):
"""Sends a sticker in a way that never triggers exceptions and logs errors"""
try:
return client.send_sticker(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def send_animation(client: Client, *args, **kwargs):
"""Sends an animation in a way that never triggers exceptions and logs errors"""
try:
return client.send_animation(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False

View File

@ -0,0 +1,29 @@
from pyrogram.errors import RPCError, FloodWait
import time
import logging
def answer(query, *args, **kwargs):
"""Answers a query in a way that never triggers exceptions and logs errors"""
try:
return query.answer(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False
def delete_messages(client, *args, **kwargs):
"""Deletes messages in a way that never triggers exceptions and logs errors"""
try:
return client.delete_messages(*args, **kwargs)
except FloodWait as fw:
logging.warning(f"FloodWait! Sleeping {fw.x} seconds")
time.sleep(fw.x)
except RPCError as generic_error:
logging.error(f"An exception occurred: {generic_error}")
return False

View File

@ -0,0 +1 @@
__version__ = (1, 0, 0)

67
BotBase/modules/admin.py Normal file
View File

@ -0,0 +1,67 @@
from ..config import ADMINS, USER_INFO, INVALID_SYNTAX, ERROR, NONNUMERIC_ID, USERS_COUNT, \
NO_PARAMETERS, ID_MISSING, GLOBAL_MESSAGE_STATS
from pyrogram import Client, Filters
from ..database.query import get_user, get_users
from .antiflood import BANNED_USERS
import random
from ..methods.safe_send import send_message
import logging
ADMINS_FILTER = Filters.user(list(ADMINS.keys()))
@Client.on_message(Filters.command("count") & ADMINS_FILTER & Filters.private & ~BANNED_USERS)
def count_users(client, message):
logging.warning(f"Admin with id {message.from_user.id} sent /count")
count = len(get_users())
send_message(client, message.chat.id, USERS_COUNT.format(count))
@Client.on_message(Filters.command("getuser") & ADMINS_FILTER & Filters.private & ~BANNED_USERS)
def get_user_info(client, message):
if len(message.command) == 2:
if message.command[1].isdigit():
user = get_user(message.command[1])
if user:
logging.warning(f"Admin with id {message.from_user.id} sent /getuser {message.command[1]}")
rowid, uid, uname, date, admin = user
text = USER_INFO.format(uid=uid, uname='@' + uname if uname != 'null' else uname, date=date, status='User' if not admin else 'Admin')
send_message(client, message.chat.id, text)
else:
send_message(client, message.chat.id, f"{ERROR}: {ID_MISSING.format(uid=message.command[1])}")
else:
send_message(client, message.chat.id, f"{ERROR}: {NONNUMERIC_ID}")
else:
send_message(client, message.chat.id, f"{INVALID_SYNTAX}: Use <code>/getuser user_id</code>")
@Client.on_message(Filters.command("getranduser") & ADMINS_FILTER & Filters.private & ~BANNED_USERS)
def get_random_user(client, message):
logging.warning(f"Admin with id {message.from_user.id} sent /getranduser")
if len(message.command) > 1:
send_message(client, message.chat.id, f"{INVALID_SYNTAX}: {NO_PARAMETERS.format(command='/getranduser')}")
else:
user = random.choice(get_users())
rowid, uid, uname, date, admin = get_user(*user)
text = USER_INFO.format(uid=uid, uname='@' + uname if uname != 'null' else uname, date=date,
status='User' if not admin else 'Admin',
)
send_message(client, message.chat.id, text)
@Client.on_message(Filters.command("global") & ADMINS_FILTER & Filters.private & ~BANNED_USERS)
def global_message(client, message):
if len(message.command) > 1:
msg = message.text.html[7:]
logging.warning(f"Admin with id {message.from_user.id} sent the following global message: {msg}")
missed = 0
count = 0
for uid in get_users():
count += 1
if not send_message(client, *uid, msg): # Returns False if an error gets raised
missed += 1
send_message(client, message.chat.id, GLOBAL_MESSAGE_STATS.format(count=count, success=(count - missed), msg=msg))
else:
send_message(client, message.chat.id, f"{INVALID_SYNTAX}: Use <code>/global message</code>"
"\n🍮 Note that the <code>/global</code> command supports markdown and html styling")

View File

@ -0,0 +1,70 @@
from pyrogram import Client, Filters, Message
from ..config import MAX_UPDATE_THRESHOLD, ANTIFLOOD_SENSIBILITY, BAN_TIME, ADMINS, BYPASS_FLOOD, FLOOD_NOTICE, \
COUNT_CALLBACKS_SEPARATELY, FLOOD_PERCENTAGE, CACHE, PRIVATE_ONLY
from collections import defaultdict
import logging
import time
from ..methods.safe_send import send_message
# Some variables for runtime configuration
MESSAGES = defaultdict(list) # Internal variable for the antiflood module
BANNED_USERS = Filters.user() # Filters where the antiflood will put banned users
BYPASS_USERS = Filters.user(list(ADMINS.keys())) if BYPASS_FLOOD else Filters.user()
QUERIES = defaultdict(list) if COUNT_CALLBACKS_SEPARATELY else MESSAGES
FILTER = Filters.private if PRIVATE_ONLY else ~Filters.user()
def is_flood(updates: list):
"""Calculates if a sequence of
updates corresponds to a flood"""
genexpr = [i <= ANTIFLOOD_SENSIBILITY for i in
((updates[i + 1] - timestamp) if i < (MAX_UPDATE_THRESHOLD - 1) else (timestamp - updates[i - 1]) for
i, timestamp in enumerate(updates))]
limit = (len(genexpr) / 100) * FLOOD_PERCENTAGE
if genexpr.count(True) >= limit:
return True
else:
return False
@Client.on_callback_query(FILTER & ~BYPASS_USERS, group=-1)
@Client.on_message(FILTER & ~BYPASS_USERS, group=-1)
def anti_flood(client, update):
"""Anti flood module"""
VAR = MESSAGES if isinstance(update, Message) else QUERIES
if isinstance(VAR[update.from_user.id], tuple):
chat, date = VAR[update.from_user.id]
if time.time() - date >= BAN_TIME:
logging.warning(f"{update.from_user.id} has waited at least {BAN_TIME} seconds and can now text again")
BANNED_USERS.remove(update.from_user.id)
del VAR[update.from_user.id]
elif len(VAR[update.from_user.id]) >= MAX_UPDATE_THRESHOLD:
logging.info(f"MAX_MESS_THRESHOLD ({MAX_UPDATE_THRESHOLD}) Reached for {update.from_user.id}")
timestamps = VAR.pop(update.from_user.id)
if is_flood(timestamps):
logging.warning(f"Flood detected from {update.from_user.id} in chat {update.chat.id}")
if update.from_user.id in CACHE:
del CACHE[update.from_user.id]
BANNED_USERS.add(update.from_user.id)
if isinstance(update, Message):
chatid = update.chat.id
else:
chatid = update.from_user.id
VAR[update.from_user.id] = chatid, time.monotonic()
if FLOOD_NOTICE:
send_message(client, update.from_user.id, FLOOD_NOTICE)
else:
if update.from_user.id in VAR:
del VAR[update.from_user.id]
else:
if isinstance(update, Message):
date = update.date
else:
if update.message:
date = update.message.date
else:
date = time.monotonic()
VAR[update.from_user.id].append(date)

151
BotBase/modules/livechat.py Normal file
View File

@ -0,0 +1,151 @@
from pyrogram import Client, Filters, InlineKeyboardMarkup, InlineKeyboardButton
from ..methods.safe_send import send_message
from ..methods.safe_edit import edit_message_text
from ..methods.various import answer, delete_messages
from ..config import CACHE, ADMINS, STATUSES, ADMINS_LIST_UPDATE_DELAY, callback_regex, admin_is_chatting, \
user_is_chatting, LIVE_CHAT_STATUSES, STATUS_BUSY, STATUS_FREE, SUPPORT_REQUEST_SENT, SUPPORT_NOTIFICATION, \
ADMIN_JOINS_CHAT, USER_CLOSES_CHAT, JOIN_CHAT_BUTTON, USER_INFO, USER_LEAVES_CHAT, ADMIN_MESSAGE, USER_MESSAGE, \
TOO_FAST, CHAT_BUSY, LEAVE_CURRENT_CHAT, USER_JOINS_CHAT
from collections import defaultdict
import time
from ..database.query import get_user
from datetime import datetime
from .antiflood import BANNED_USERS
from .start import back_start
CHATS = defaultdict(None)
NAME = "tg://user?id={}"
ADMINS_FILTER = Filters.user(list(ADMINS.keys()))
BUTTONS = InlineKeyboardMarkup(
[[InlineKeyboardButton("🔙 Back", "back_start")], [InlineKeyboardButton("🔄 Update", "update_admins_list")]])
@Client.on_callback_query(Filters.callback_data("sos") & ~BANNED_USERS)
def begin_chat(_, query):
CACHE[query.from_user.id] = ["AWAITING_ADMIN", time.time()]
queue = LIVE_CHAT_STATUSES
for admin_id, data in STATUSES.items():
admin_name, status = data
if status == "free":
queue += f"- {STATUS_FREE}"
else:
queue += f"- {STATUS_BUSY}"
queue += f"[{admin_name}]({NAME.format(admin_id)})\n"
msg = edit_message_text(query, SUPPORT_REQUEST_SENT.format(queue=queue, date=time.strftime('%d/%m/%Y %T')),
reply_markup=BUTTONS)
join_chat_button = InlineKeyboardMarkup([[InlineKeyboardButton(JOIN_CHAT_BUTTON, f"join_{query.from_user.id}")]])
user = get_user(query.from_user.id)
rowid, uid, uname, date, last_call, imei = user
admin = uid in ADMINS
text = USER_INFO.format(uid=uid, uname='@' + uname if uname != 'null' else uname, date=date,
status='User' if not admin else 'Admin',
last_call=datetime.utcfromtimestamp(int(last_call)), imei=imei)
CACHE[query.from_user.id].append([])
for admin in ADMINS:
message = send_message(_, admin, SUPPORT_NOTIFICATION.format(uinfo=text), reply_markup=join_chat_button)
CACHE[query.from_user.id][-1].append((message.chat.id, message.message_id))
CACHE[query.from_user.id][-1].append((msg.chat.id, msg.message_id))
@Client.on_callback_query(Filters.callback_data("update_admins_list") & ~BANNED_USERS)
def update_admins_list(_, query):
if time.time() - CACHE[query.from_user.id][1] >= ADMINS_LIST_UPDATE_DELAY:
if CACHE[query.from_user.id][0] == "AWAITING_ADMIN":
CACHE[query.from_user.id] = ["AWAITING_ADMIN", time.time()]
queue = LIVE_CHAT_STATUSES
for admin_id, data in STATUSES.items():
admin_name, status = data
if status == "free":
queue += f"- {STATUS_FREE}"
else:
queue += f"- {STATUS_BUSY}"
queue += f"[{admin_name}]({NAME.format(admin_id)})\n"
edit_message_text(query, SUPPORT_REQUEST_SENT.format(queue=queue, date=time.strftime('%d/%m/%Y %T')),
reply_markup=BUTTONS)
else:
back_start(_, query)
else:
answer(query, TOO_FAST, show_alert=True)
@Client.on_callback_query(callback_regex(r"close_chat_\d+") & ~BANNED_USERS)
def close_chat(_, query):
if user_is_chatting() or admin_is_chatting():
user_id = int(query.data.split("_")[2])
if query.from_user.id in ADMINS:
data = CACHE[CACHE[query.from_user.id][1]][-1]
if isinstance(data, list):
for chatid, message_ids in data:
delete_messages(_, chatid, message_ids)
if STATUSES[query.from_user.id][1] != "free":
STATUSES[query.from_user.id][1] = "free"
admin_id, admin_name = query.from_user.id, STATUSES[query.from_user.id][0]
edit_message_text(query, USER_LEAVES_CHAT)
if CACHE[user_id][1]:
send_message(_, user_id,
USER_CLOSES_CHAT.format(user_id=NAME.format(admin_id), user_name=admin_name))
if user_id in CACHE:
del CACHE[user_id]
del CACHE[admin_id]
else:
data = CACHE[query.from_user.id][-1]
if isinstance(data, list):
for chatid, message_ids in data:
delete_messages(_, chatid, message_ids)
admin_id = CACHE[query.from_user.id][1]
if CACHE[user_id][1]:
if query.from_user.first_name:
user_name = query.from_user.first_name
elif query.from_user.username:
user_name = query.from_user.username
else:
user_name = "Anonymous"
edit_message_text(query, USER_LEAVES_CHAT)
send_message(_, CACHE[user_id][1],
USER_CLOSES_CHAT.format(user_id=NAME.format(query.from_user.id), user_name=user_name))
del CACHE[query.from_user.id]
del CACHE[admin_id]
else:
back_start(_, query)
@Client.on_message(ADMINS_FILTER & Filters.private & admin_is_chatting() & Filters.text & ~BANNED_USERS)
def forward_from_admin(client, message):
send_message(client, STATUSES[message.from_user.id][1],
ADMIN_MESSAGE.format(STATUSES[message.from_user.id][0], NAME.format(message.from_user.id),
message.text.html))
@Client.on_message(user_is_chatting() & Filters.text & ~BANNED_USERS)
def forward_from_user(client, message):
if message.from_user.first_name:
name = message.from_user.first_name
elif message.from_user.username:
name = message.from_user.username
else:
name = "Anonymous"
send_message(client, CACHE[message.from_user.id][1],
USER_MESSAGE.format(user_name=name, user_id=NAME.format(message.from_user.id),
message=message.text.html))
@Client.on_callback_query(ADMINS_FILTER & callback_regex(r"join_\d+") & ~BANNED_USERS)
def join_chat(_, query):
if CACHE[query.from_user.id][0] != "IN_CHAT":
user_id = int(query.data.split("_")[1])
if CACHE[user_id][0] != "AWAITING_ADMIN":
answer(query, CHAT_BUSY)
else:
buttons = InlineKeyboardMarkup([[InlineKeyboardButton("❌ Close chat", f"close_chat_{user_id}")]])
admin_id, admin_name = query.from_user.id, STATUSES[query.from_user.id][0]
STATUSES[query.from_user.id][1] = user_id
CACHE[user_id] = ["IN_CHAT", admin_id, CACHE[user_id][-1]]
CACHE[query.from_user.id] = ["IN_CHAT", user_id]
message = send_message(_, query.from_user.id, USER_JOINS_CHAT, reply_markup=buttons)
send_message(_, user_id, ADMIN_JOINS_CHAT.format(admin_name=admin_name, admin_id=NAME.format(admin_id)),
reply_markup=buttons)
for chatid, message_ids in CACHE[CACHE[query.from_user.id][1]][-1]:
delete_messages(_, chatid, message_ids)
CACHE[user_id][-1].append((message.chat.id, message.message_id))
else:
answer(query, LEAVE_CURRENT_CHAT)

32
BotBase/modules/start.py Normal file
View File

@ -0,0 +1,32 @@
from pyrogram import Client, Filters, InlineKeyboardButton, InlineKeyboardMarkup
from .antiflood import BANNED_USERS
from ..config import GREET, BUTTONS, CREDITS
from ..database.query import get_users, set_user
import logging
import itertools
from ..methods.safe_send import send_message
from ..methods.safe_edit import edit_message_text
@Client.on_message(Filters.command("start") & ~BANNED_USERS & Filters.private)
def start_handler(client, message):
"""Simply handles the /start command sending a pre-defined greeting
and saving new users to the database"""
if message.from_user.first_name:
name = message.from_user.first_name
elif message.from_user.username:
name = message.from_user.username
else:
name = "Anonymous"
if message.from_user.id not in itertools.chain(*get_users()):
logging.warning(f"New user detected ({message.from_user.id}), adding to database")
set_user(message.from_user.id, None if not message.from_user.username else message.from_user.username)
send_message(client, message.chat.id, GREET.format(mention=f"[{name}](tg://user?id={message.from_user.id})"),
reply_markup=BUTTONS)
@Client.on_callback_query(Filters.callback_data("info"))
def bot_info(_, query):
buttons = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back", "back_start")]])
edit_message_text(query, CREDITS, reply_markup=buttons)

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

44
bot.py Normal file
View File

@ -0,0 +1,44 @@
import logging
from pyrogram import Client
import sqlite3.dbapi2 as sqlite3
import os
from pyrogram.session import Session
import importlib
def create_database(path: str, query: str):
if os.path.exists(path):
logging.warning(f"Database file exists at {path}, running query")
else:
logging.warning(f"No database found, creating it at {path}")
try:
database = sqlite3.connect(path)
except sqlite3.Error as connection_error:
logging.error(f"An error has occurred while connecting to database: {connection_error}")
else:
try:
with database:
cursor = database.cursor()
cursor.executescript(query)
cursor.close()
except sqlite3.Error as query_error:
logging.info(f"An error has occurred while executing query: {query_error}")
if __name__ == "__main__":
MODULE_NAME = "BotBase"
conf = importlib.import_module(MODULE_NAME)
logging.basicConfig(format=conf.LOGGING_FORMAT, datefmt=conf.DATE_FORMAT, level=conf.LOGGING_LEVEL)
bot = Client(api_id=conf.API_ID, api_hash=conf.API_HASH, bot_token=conf.BOT_TOKEN, plugins=conf.PLUGINS_ROOT,
session_name=conf.SESSION_NAME, workers=conf.WORKERS_NUM)
Session.notice_displayed = True
try:
logging.warning("Running create_database()")
create_database(conf.DB_RELPATH, conf.DB_CREATE)
logging.warning("Database interaction complete")
logging.warning("Starting bot")
bot.start()
logging.warning("Bot started")
except KeyboardInterrupt:
logging.warning("Stopping bot")
bot.stop()

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
pyrogram
tgcrypto