Бот написан на telebot python .Не работает переключение между чатами и переключение между ID. В коде должен быть один чат техподдержки. Как сделать, чтобы при переписке с поддержкой сообщения не спамились, а потом, когда поддержка выбирала чат и при нажатии выводила сообщения? Так-же данные должны записываться в exel файл.
Помогите с решением проблемы.
import telebot
import pandas as pd
from telebot import types
bot = telebot.TeleBot('token')
SUPPORT_CHAT_ID = id_teh_podder
chats = {}
excel_file = 'chats.xlsx'
class ChatState:
def __init__(self):
self.current_page = 0
self.page_size = 10
def update_page(self, delta):
self.current_page += delta
if self.current_page < 0:
self.current_page = 0
def get_page_indexes(self):
start_index = self.current_page * self.page_size
end_index = start_index + self.page_size
return start_index, end_index
def has_prev_page(self):
return self.current_page > 0
def has_next_page(self, chat_list):
start_index, _ = self.get_page_indexes()
return start_index + self.page_size < len(chat_list)
state = ChatState()
def save_chats_to_excel():
chat_data = {'ChatID': list(chats.keys()), 'user_id': list(chats.values())}
df = pd.DataFrame(chat_data)
df.to_excel(excel_file, index=False)
def load_chats_from_excel():
try:
df = pd.read_excel(excel_file)
if 'ChatID' in df.columns and 'user_id' in df.columns:
chats.update(zip(df['ChatID'], df['user_id']))
else:
print("Invalid column names in the Excel file.")
except FileNotFoundError:
pass
def is_valid_chat(chat_id):
return chat_id in chats.keys()
def get_chat_buttons():
buttons = []
chat_list = list(chats.keys())
start_index, end_index = state.get_page_indexes()
for chat_id in chat_list[start_index:end_index]:
button = types.InlineKeyboardButton(
str(chat_id), callback_data=f'switch_{chat_id}')
buttons.append(button)
keyboard = types.InlineKeyboardMarkup(row_width=2)
keyboard.add(*buttons)
if state.has_prev_page():
prev_button = types.InlineKeyboardButton(
'Previous', callback_data='prev_page')
keyboard.add(prev_button)
if state.has_next_page(chat_list):
next_button = types.InlineKeyboardButton(
'Next', callback_data='next_page')
keyboard.add(next_button)
stop_button = types.InlineKeyboardButton('Stop', callback_data='stop')
keyboard.add(stop_button)
return keyboard
@bot.message_handler(commands=['start'])
def start_handler(message):
chat_id = message.chat.id
chats[chat_id] = SUPPORT_CHAT_ID
bot.send_message(chat_id, 'You are connected to the support team.')
save_chats_to_excel()
@bot.message_handler(commands=['switch'])
def switch_handler(message):
chat_id = message.chat.id
bot.send_message(chat_id, 'Please select a chat to switch to:',
reply_markup=get_chat_buttons())
@bot.callback_query_handler(lambda call: call.data.startswith('switch'))
def switch_callback_handler(call):
chat_id = call.message.chat.id
selected_chat_id = call.data.split('_')[1]
if is_valid_chat(chat_id):
if selected_chat_id in chats:
chats[SUPPORT_CHAT_ID] = selected_chat_id
bot.send_message(
SUPPORT_CHAT_ID, f'Switched to chat {selected_chat_id}.')
bot.send_message(
selected_chat_id, 'You are now connected to the support team.')
bot.send_message(
chat_id, 'You are now connected to the selected chat.')
else:
bot.send_message(
SUPPORT_CHAT_ID, f'No chat found with chat {selected_chat_id}.')
else:
bot.send_message(chat_id, 'You are not authorized to switch chats.')
save_chats_to_excel()
@bot.callback_query_handler(func=lambda call: call.data == 'prev_page')
def prev_page_callback_handler(call):
chat_id = call.message.chat.id
if chat_id == SUPPORT_CHAT_ID:
state.update_page(-1)
bot.edit_message_reply_markup(
chat_id, call.message.message_id, reply_markup=get_chat_buttons())
@bot.callback_query_handler(func=lambda call: call.data == 'next_page')
def next_page_callback_handler(call):
chat_id = call.message.chat.id
if chat_id == SUPPORT_CHAT_ID:
state.update_page(1)
bot.edit_message_reply_markup(
chat_id, call.message.message_id, reply_markup=get_chat_buttons())
@bot.callback_query_handler(func=lambda call: call.data == 'stop')
def stop_callback_handler(call):
chat_id = call.message.chat.id
if chat_id == SUPPORT_CHAT_ID:
bot.edit_message_reply_markup(
chat_id, call.message.message_id, reply_markup=None)
else:
bot.send_message(
chat_id, 'You are not authorized to stop the chat selection.')
@bot.message_handler(func=lambda message: True)
def message_handler(message):
chat_id = message.chat.id
if chat_id == SUPPORT_CHAT_ID:
bot.send_message(
chat_id, f'Response from chat {chat_id}: {message.text}')
bot.send_message(chat_id, 'Message sent to the support team.')
else:
support_chat_id = chats.get(chat_id, SUPPORT_CHAT_ID)
if support_chat_id == SUPPORT_CHAT_ID:
bot.send_message(
chat_id, f'Response from chat {chat_id}: {message.text}')
bot.send_message(chat_id, 'Message sent to the support team.')
else:
bot.send_message(
chat_id, 'You are not connected to the support team. Use /start command to connect.', reply_to_message_id=message.message_id)
save_chats_to_excel()
load_chats_from_excel()
bot.polling()