Telegram bot on python for Steem-Song
Hi everyone!
An update for the Steem-Song bot is finally ready.
Todo list:
Authorization of participants. (!)
Button "Cabinet"
When you press the "Cabinet" button - a list of recorded audio and next to each number of likes and dislikes.
Like and dislike buttons under each given audio message.
Ability to click like and dislike to vote
Admin - panel., with the ability to listen and delete messages.
Counter of audio messages (how many) with the ability to output to the chat (where I will add the bot) on request. Those. output command the total number of audio in the database
Ratings by the number of likes and dislikes
Ability to output random audio to a group on command (telegram chat)
Do not resend! Audio
??????????????????
✅✅✅✅✅
✅✅❌❌❌
❌❌❌❌❌
❌❌❌❌❌
✅✅✅✅✅
✅✅✅✅✅
❌❌❌❌❌
✅✅✅✅❌
❌❌❌❌❌
script:
import telebot
from telebot import types
from datetime import datetime
import requests
import random
import json
import os
import sqlite3 as sq
import text as tx
token = '5471541630:AAGq36-3LJBQmpQmITc_tRihq3OXff086Jc'
bot = telebot.TeleBot(token)
db_name = "main_database.db"
developer_id = 516352068
admin_id = 221901211
main_folder = 'voices'
def program_setting():
if not os.path.exists(main_folder):
os.mkdir(main_folder)
def keyboard(*buttons, row_width=2):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=row_width)
for button in buttons:
markup.add(types.KeyboardButton(button))
return markup
@bot.message_handler(commands=['start'])
def start(message):
if message.chat.id == admin_id:
markup = keyboard(tx.button_panel)
else:
markup = keyboard(tx.button_instruction, tx.button_cabinet)
bd_id = "{0.id}".format(message.from_user)
bd_un = "{0.username}".format(message.from_user)
bd_fn = "{0.first_name}".format(message.from_user)
bd_ln = "{0.last_name}".format(message.from_user)
try:
with sq.connect(db_name) as con:
cur = con.cursor()
bd_request = 'SELECT * FROM users WHERE id_chat = ' + bd_id
cur.execute(bd_request)
exist = cur.fetchone()
if exist is None:
cur.execute("INSERT INTO users (id_chat, username, first_name, last_name) VALUES (?, ?, ?, ?)",
(bd_id, bd_un, bd_fn, bd_ln))
except sq.OperationalError as oe:
print(oe)
bot.send_message(message.chat.id, tx.start, reply_markup=markup)
@bot.message_handler(commands=['count'])
def count(message):
if message.chat.id == admin_id:
with sq.connect(db_name) as con:
bot.send_message(admin_id, f"Всего аудио: {con.execute('SELECT Count(*) FROM audio').fetchone()[0]}",
parse_mode='HTML')
@bot.message_handler(commands=['audio'])
def count(message):
if message.chat.id == admin_id:
all_voices = []
files = os.listdir(main_folder)
for file in files:
if file.endswith('.ogg'):
all_voices.append(file)
if all_voices:
with open(f'{main_folder}/{random.choice(all_voices)}', 'rb') as f:
bot.send_audio(message.chat.id, f)
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
json_string = json.loads(call.data)
method = json_string['method']
path_audio = json_string['path']
with sq.connect(db_name) as con:
if method == 'verify':
con.execute(f"UPDATE audio SET approved = 1 WHERE path = '{path_audio}'")
bot.send_message(admin_id, 'Запись проверена!')
if method == 'delete':
con.execute(f"DELETE FROM audio WHERE path = '{path_audio}'")
os.remove(path_audio)
bot.send_message(admin_id, 'Запись удалена!')
if method == 'isolation':
con.execute(f"UPDATE audio SET approved = 2 WHERE path = '{path_audio}'")
bot.send_message(admin_id, '> Добавлено в Карантин, однако функция находиться в разработке <')
@bot.message_handler(content_types=['voice'])
def repeat_all_message(message):
all_voices = []
files = os.listdir(main_folder)
for file in files:
if file.endswith('.ogg'):
all_voices.append(file)
if all_voices:
with open(f'{main_folder}/{random.choice(all_voices)}', 'rb') as f:
bot.send_audio(message.chat.id, f)
now = datetime.now().strftime("%Y%m%d%I%M")
file_info = bot.get_file(message.voice.file_id)
file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(token, file_info.file_path))
file_presence = True
path_file = ''
i = 0
while file_presence:
i += 1
if i == 1:
path_file = f'{main_folder}/voice({now}).ogg'
else:
path_file = f'{main_folder}/voice({now})_{str(i)}.ogg'
if not os.path.exists(path_file):
with open(path_file, 'wb') as f:
f.write(file.content)
file_presence = False
try:
bd_id = "{0.id}".format(message.from_user)
with sq.connect(db_name) as con:
con.cursor().execute("INSERT INTO audio (user_id, path) VALUES (?, ?)", (bd_id, path_file))
except sq.OperationalError as oe:
print(oe)
@bot.message_handler(content_types=["text"])
def all_messages(message):
def audio_settings(proved, method):
with sq.connect(db_name) as con:
all_unapproved = con.execute(f'SELECT * FROM audio WHERE approved = {proved}').fetchall()
for unapproved in all_unapproved:
path_audio = unapproved[2]
with open(path_audio, 'rb') as f:
markup_audio = types.InlineKeyboardMarkup()
button_delete = types.InlineKeyboardButton(
'Удалить', callback_data="{"method":"delete","path":"" + str(path_audio) + ""}")
if method == 'verify':
button_verify = types.InlineKeyboardButton(
'Одобрить', callback_data="{"method":"verify","path":"" + str(path_audio) + ""}")
if method == 'checked':
button_verify = types.InlineKeyboardButton(
'Карантин', callback_data="{"method":"isolation","path":"" + str(path_audio) + ""}")
markup_audio.add(button_delete, button_verify)
bot.send_audio(message.chat.id, f, reply_markup=markup_audio)
def my_audio():
with sq.connect(db_name) as con:
audio_request = con.execute(f'SELECT * FROM audio WHERE user_id = {str(message.chat.id)}').fetchall()
for audio in audio_request:
path_audio = audio[2]
with open(path_audio, 'rb') as f:
bot.send_audio(message.chat.id, f)
if message.chat.id == admin_id:
if message.text == tx.button_panel:
markup = keyboard(tx.button_approved, tx.button_unapproved, tx.button_isolation)
bot.send_message(message.chat.id, random.choice(tx.answers_for_admin), reply_markup=markup)
if message.text == tx.button_unapproved:
audio_settings(0, 'verify')
if message.text == tx.button_approved:
audio_settings(1, 'checked')
if message.text == tx.button_isolation:
audio_settings(2, 'verify')
else:
if message.text == tx.button_instruction:
bot.send_message(message.chat.id, tx.instruction)
elif message.text == tx.button_cabinet:
my_audio()
else:
bot.send_message(message.chat.id, tx.audio)
if name == 'main':
program_setting()
# bot.send_message(developer_id, 'Босс, бот запущен 😎')
bot.infinity_polling()