@aboba234

Почему выходит сообщение A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: chat not found?

RestFunc = {}
TOKEN = "" 
ADMIN = [] 



GROUPS = [[], []]  




START = "Привет! Для рассылки нажми Рассылка"
SPAM = "Отправьте текст ✏️"
CHOICE_GROUP = " "
RESTART_SPAM = " Выбран рестарт выбора рассылки"
OTHER = " Не распознанная команда"
USE_TO = " Спасибо, что разбили нашего бота"
EXIT = " Отмена успешна"
NO_SUPPORT = "Такое не поддерживается системой"
FINISH = "Рассылка окончилась"

DIGIT_GROUP_1 = "Ваше число меньше ID GROUP"
DIGIT_GROUP_2 = "Ваше число больше ID GROUP"
DIGIT_GROUP_3 = "Нет цифр - нет рассылки"



# utils 

def get_date(d=None, format_="%Y-%m-%d-%H.%M.%S"):
	if d:
                return d.strftime(format_)
	return datetime.now().strftime(format_)

def __sender_msg(f, *args, **kwd):
	return lambda chats: [f(i, *args, **kwd) for i in chats]

class Logging:
	BASE = "[{type}] {text} [{type}]"
	
	@staticmethod
	def _(type, text, **kwd):
		bot.send_message(ADMIN[0], Logging.BASE.format(type=type, text=text), **kwd)
	
	@staticmethod
	def info(text, **kwd):
		Logging._("INFO", text, **kwd)

	@staticmethod
	def warning(text, **kwd):
		Logging._("WARNING", text, **kwd)

	@staticmethod
	def error(text, **kwd):
		Logging._("ERROR", text, **kwd)




def auth_decorator(admins):
	def decorated(f):
		f.count = 0
		f.users = {}
		RestFunc[f.__name__] = f
		bot.message_handler(commands=[f"getResult_{f.__name__}"], func=lambda m: m.from_user.id == ADMIN[0])(lambda m: bot.send_message(m.chat.id, f"Result_{f.__name__}: All request - {f.count}\nUser Data - {f.users}"))
		@wraps(f)
		def wrapper(telegram_type):
			if telegram_type.from_user.id in admins:
				f.count += 1
				if isinstance(telegram_type, Message):
					if f.users.get(telegram_type.from_user.id) is None:
						f.users[telegram_type.from_user.id] = {"count": 1, "res": [{"date": get_date(), "text": telegram_type.text if telegram_type.text else "(No Text)"}]}
					else:
						d = f.users[telegram_type.from_user.id]
						d["count"] += 1
						d["res"].append({"date": get_date(), "text": telegram_type.text if telegram_type.text else "(No Text)"})
						f.users[telegram_type.from_user.id] = d 

				return f(telegram_type)
			else:
				Logging.warning(f"Попытка соедениться с ботом, функция - {f.__name__}, юзер - id{telegram_type.from_user.id} @{telegram_type.from_user.username} {telegram_type.from_user.first_name}", parse_mode=None)
		return wrapper
	return decorated


bot = TeleBot(token=TOKEN, parse_mode="html", threaded=True, num_threads=10) 


@bot.message_handler(commands=["start"])
@auth_decorator(ADMIN)
def start(m): 
	bot.send_message(m.chat.id, START, 
		reply_markup=ReplyKeyboardMarkup(False).add("Рассылка"))


@bot.message_handler(func=lambda m: m.text.lower() == "рассылка")
@auth_decorator(ADMIN)
def rassulka(m):
	bot.send_message(m.chat.id, SPAM)
	bot.register_next_step_handler(m, pars_rassukla_typ)



@bot.callback_query_handler(func=lambda c: c.data in ("spam_yes", "spam_no"))
@auth_decorator(ADMIN)
def restart_spam(call):
	if call.data == "spam_yes":
		bot.answer_callback_query(call.id, show_alert=True, text=RESTART_SPAM)
		bot.edit_message_text(SPAM, chat_id=call.message.chat.id, message_id=call.message.message_id)
		bot.register_next_step_handler(call.message, pars_rassukla_typ)
	else:
		bot.answer_callback_query(call.id, show_alert=False, text=EXIT)
		bot.edit_message_text(USE_TO, chat_id=call.message.chat.id, message_id=call.message.message_id)


@bot.message_handler()
@auth_decorator(ADMIN)
def other(m):
	bot.send_message(m.chat.id, OTHER)


def pars_rassukla_typ(m):
	if m.text == "-":
		bot.send_message(m.chat.id, EXIT)
		return
	if m.content_type == "text":
		f = __sender_msg(bot.send_message, m.text)
	else:
		if m.content_type in ["document", "photo", "video"]:
			media_tg = getattr(m, m.content_type)
			if m.content_type == "document":
				f = __sender_msg(bot.send_document, media_tg.file_id, caption=m.caption)
			elif m.content_type == "photo":
				f = __sender_msg(bot.send_photo, media_tg[-1].file_id, caption=m.caption)
			elif m.content_type == "video":
				f = __sender_msg(bot.send_video, media_tg.file_id, caption=m.caption)
		else:
			return bot.send_message(m.chat.id, NO_SUPPORT)
	bot.register_next_step_handler(m, get_group_list, f)
	bot.send_message(m.chat.id, CHOICE_GROUP.format(group=len(GROUPS)))


	


def get_group_list(m, f):
	if m.text == "-":
		bot.send_message(m.chat.id, EXIT)
		return

	if m.text.isdigit():
		if int(m.text) <= len(GROUPS): 
			if int(m.text) > 0:
				groups = GROUPS[int(m.text)-1]
				f(groups)
				msg = bot.send_message(m.chat.id, FINISH, reply_markup=InlineKeyboardMarkup().add(InlineKeyboardButton("Продолжить?", callback_data="323")).row(InlineKeyboardButton("---", callback_data="122")).row(InlineKeyboardButton("Да", callback_data="spam_yes"), InlineKeyboardButton("Нет", callback_data="spam_no")).row(InlineKeyboardButton("---", callback_data="233wdwd")))
				sleep(600)
				try:
					bot.edit_message_reply_markup(chat_id=m.chat.id, message_id=msg.message_id)
				except:
					pass 
				return
			else:
				bot.send_message(m.chat.id, DIGIT_GROUP_1)
		else:
			bot.send_message(m.chat.id, DIGIT_GROUP_2)
	else:
		bot.send_message(m.chat.id, DIGIT_GROUP_3)

	bot.register_next_step_handler(m, get_group_list, f)
	bot.send_message(m.chat.id, CHOICE_GROUP.format(group=len(GROUPS)))
	



if __name__ == '__main__':
	print("Run")
	while True:
		try:
			bot.polling(none_stop=True, skip_pending=True)
		except Exception as e:
			print(e)
			sleep(3)
			Logging.error(str(e))
			sleep(1)
  • Вопрос задан
  • 90 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы