-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram_bot.py
More file actions
168 lines (128 loc) · 7.39 KB
/
telegram_bot.py
File metadata and controls
168 lines (128 loc) · 7.39 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import os
import speech_recognition as sr
import subprocess
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, CommandHandler, ContextTypes, filters
from bot import bot
import db
TOKEN = '8543722157:AAFbvEtHXBkTUdloiDNIpxov98MrzEwraug'
# Определяем путь к ffmpeg
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FFMPEG_PATH = os.path.join(BASE_DIR, "ffmpeg", "bin", "ffmpeg.exe")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Привет! Я бот по ремонту авто. Напиши или отправь голосовое сообщение.")
async def handle_voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.message.from_user
user_db_id = db.save_user(user) # Сохраняем пользователя
voice_file = await update.message.voice.get_file()
file_data = await voice_file.download_as_bytearray()
# Сохраняем голосовое сообщение
ogg_file = 'user_voice.ogg'
wav_file = 'user_voice.wav'
with open(ogg_file, 'wb') as f:
f.write(file_data)
audio_file = None # Инициализируем переменную заранее
try:
# Конвертация ogg в wav с помощью ffmpeg
print(f"Конвертация {ogg_file} в {wav_file}...")
# Проверяем, существует ли ffmpeg
if not os.path.exists(FFMPEG_PATH):
print(f"FFmpeg не найден по пути: {FFMPEG_PATH}")
await update.message.reply_text("Ошибка: FFmpeg не установлен. Пожалуйста, напишите текстом.")
return
# Команда для конвертации
cmd = [FFMPEG_PATH, '-i', ogg_file, '-acodec', 'pcm_s16le', '-ar', '16000', '-ac', '1', wav_file]
print(f"Выполняем команду: {' '.join(cmd)}")
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
print(f"Ошибка ffmpeg: {result.stderr}")
await update.message.reply_text("Ошибка при конвертации аудио. Попробуйте отправить текстом.")
return
print("Конвертация успешно завершена!")
except subprocess.TimeoutExpired:
print("Таймаут при конвертации аудио")
await update.message.reply_text("Таймаут при обработке аудио. Попробуйте снова.")
return
except Exception as e:
print(f"Ошибка при запуске ffmpeg: {e}")
await update.message.reply_text(f"Ошибка обработки: {str(e)}")
return
if not os.path.exists(wav_file):
await update.message.reply_text("Не удалось создать файл .wav. Попробуйте снова.")
return
# Распознаем текст
recognizer = sr.Recognizer()
try:
with sr.AudioFile(wav_file) as source:
# Уменьшаем шум и настраиваем чувствительность
recognizer.adjust_for_ambient_noise(source, duration=0.5)
audio_data = recognizer.record(source)
user_message = recognizer.recognize_google(audio_data, language="ru-RU")
print(f"Распознанный текст: {user_message}")
await update.message.reply_text(f"Вы сказали: {user_message}")
# Получаем ответ от бота
response, audio_file = bot(user_message)
db.log_interaction(user_db_id, user_message, response) # Логируем взаимодействие
await update.message.reply_text(response)
# Отправляем аудиоответ, если он создан
if audio_file and os.path.exists(audio_file):
with open(audio_file, 'rb') as voice:
await update.message.reply_voice(voice)
else:
print(f"Аудиофайл не найден: {audio_file}")
except sr.UnknownValueError:
await update.message.reply_text("Не удалось распознать речь. Пожалуйста, повторите или напишите текстом.")
except sr.RequestError as e:
print(f"Ошибка сервиса распознавания: {e}")
await update.message.reply_text("Ошибка сервиса распознавания речи. Попробуйте позже.")
except Exception as e:
print(f"Ошибка при распознавании: {e}")
await update.message.reply_text(f"Ошибка при распознавании: {str(e)}")
except Exception as e:
print(f"Общая ошибка: {e}")
await update.message.reply_text(f"Произошла непредвиденная ошибка: {str(e)}")
finally:
# Очищаем временные файлы
cleanup_files = []
if audio_file:
cleanup_files.append(audio_file)
cleanup_files.extend([wav_file, ogg_file])
for file_path in cleanup_files:
try:
if file_path and os.path.exists(file_path):
os.remove(file_path)
print(f"Удален файл: {file_path}")
except Exception as e:
print(f"Ошибка при удалении {file_path}: {e}")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.message.from_user
user_db_id = db.save_user(user) # Сохраняем пользователя
user_message = update.message.text
print(f"Получено текстовое сообщение: {user_message}")
try:
response, audio_file = bot(user_message)
db.log_interaction(user_db_id, user_message, response) # Логируем взаимодействие
await update.message.reply_text(response)
if audio_file and os.path.exists(audio_file):
with open(audio_file, 'rb') as voice:
await update.message.reply_voice(voice)
os.remove(audio_file)
print(f"Аудиоответ отправлен и удален: {audio_file}")
else:
await update.message.reply_text("Не удалось сгенерировать аудиоответ.")
except Exception as e:
print(f"Ошибка при обработке текстового сообщения: {e}")
await update.message.reply_text(f"Произошла ошибка: {str(e)}")
def main():
db.init_db() # Инициализация БД
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.add_handler(MessageHandler(filters.VOICE, handle_voice_message))
print("✅ Бот запущен...")
print(f"FFmpeg путь: {FFMPEG_PATH}")
print(f"FFmpeg существует: {os.path.exists(FFMPEG_PATH)}")
app.run_polling()
if __name__ == '__main__':
main()