-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
83 lines (69 loc) · 2.52 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import os
import logging
import requests
from pymongo import MongoClient
import telebot
API_TOKEN = os.environ['BOT_TOKEN']
DB = os.environ['BOT_DB']
bot = telebot.TeleBot(API_TOKEN)
client = MongoClient(DB)
db = client.bot_db
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)
@bot.message_handler(commands=['start'])
def send_welcome_contoller(message):
chat_id = message.chat.id
text = 'Hi! You can send voice note to me and I will save it.'
bot.send_message(chat_id, text)
@bot.message_handler(commands=['get_files'])
def get_list_files_contoller(message):
chat_id = message.chat.id
user_id = message.from_user.id
if db.files.count_documents({"user_id": user_id}) > 0:
list_ = db.files.find({"user_id": user_id})
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True)
for file in list_:
markup.add(
telebot.types.KeyboardButton(text=f'/get_file {file["id"]}'))
text = 'Please choose file:'
bot.send_message(chat_id, text, reply_markup=markup)
else:
text = 'Files not found'
bot.send_message(chat_id, text)
@bot.message_handler(commands=['get_file'])
def get_file_contoller(message):
user_id = message.from_user.id
chat_id = message.chat.id
try:
id = message.text.split(' ')[1]
file = db.files.find_one({"user_id": user_id, "id": int(id)})
if file is not None:
file_path = file['path']
voice = open(file_path, 'rb')
bot.send_voice(chat_id, voice)
else:
text = 'File not found'
bot.send_message(user_id, text)
except IndexError:
print(IndexError)
text = 'Please specify file id'
bot.send_message(user_id, text)
@bot.message_handler(content_types=['voice'])
def save_voice_file_contoller(message):
file_id = message.voice.file_id
user_id = message.from_user.id
date = message.date
id = save_voice_file(file_id, user_id, date)
bot.reply_to(message, f"ок: {id}")
def save_voice_file(file_id, user_id, date):
file_info = bot.get_file(file_id)
response = requests.get(
f'https://api.telegram.org/file/bot{API_TOKEN}/{file_info.file_path}')
path = f'uploads/{file_id}.ogg'
with open(path, 'wb') as output:
output.write(response.content)
count = db.files.count_documents({"user_id": user_id})
data = {"id": count + 1, "path": path, "user_id": user_id, "date": date}
result = db.files.insert_one(data)
return data["id"]
bot.polling()