@kibernetshow

Как передать переменную из одной функции в другую?

Пишу телеграм бота и появилась такая проблемка... Нужно передать несколько переменных из одной функции в другую.
Попробовал через callback_data кнопок, но строки длинные и этот способ отпал.
Попробовал через глобальную переменную, но тоже возникли проблемы и не получилось.

Сам код
from telebot.types import InputMediaPhoto
from telebot import types
import telebot

token = ""
get_id = ""
channel_id = ""
admin_id = []

choice_keyboard = types.InlineKeyboardMarkup()
choice_keyboard.row(
	telebot.types.InlineKeyboardButton("Отправить✅", callback_data = "choice_send"),
	telebot.types.InlineKeyboardButton("Удалить❌", callback_data = "choice_remove"))


bot = telebot.TeleBot(token)
print("Bot was started.")

@bot.message_handler(commands=["send"])
def start_message(message):
	if message.from_user.id in admin_id:
		msg = bot.send_message(message.from_user.id, "Отправьте сообщение для отправки")
		bot.register_next_step_handler(msg, send_message_to_channel)
	else:
		bot.send_message(message.from_user.id, "Вы не являетесь администратором❌")


def send_message_to_channel(message):
	if message.content_type == "text":
		# Эти 3 переменные ниже нужно передать
		# send_type = "text"
		# send_data = message.text
		# send_caption = ""
		bot.send_message(message.from_user.id, message.text, reply_markup = choice_keyboard)
	if message.content_type == "photo":
		# Эти 3 переменные ниже нужно передать
		# send_type = "photo"
		# send_data = message.photo[0].file_id
		# send_caption = message.caption
		bot.send_photo(message.from_user.id, message.photo[0].file_id, caption = message.caption, reply_markup = choice_keyboard)

@bot.callback_query_handler(func = lambda call: True)
def iq_callback(call):
	if "choice_send" in call.data:
		pass #Тут вывести переменные

bot.polling(none_stop = True, interval = 0)
  • Вопрос задан
  • 2262 просмотра
Решения вопроса 2
@i_vovani
Создать глобальный словарь и сохранять значения туда,а потом доставать
Ответ написан
Комментировать
@kibernetshow Автор вопроса
Решённый вариант
from telebot.types import InputMediaPhoto
from telebot import types
import telebot

token = ""
get_id = ""
channel_id = ""
admin_id = []
get_data = []

choice_keyboard = types.InlineKeyboardMarkup()
choice_keyboard.row(
	telebot.types.InlineKeyboardButton("Отправить✅", callback_data = "choice_send"),
	telebot.types.InlineKeyboardButton("Удалить❌", callback_data = "choice_remove"))


bot = telebot.TeleBot(token)
print("Bot was started.")

@bot.message_handler(commands=["send"])
def start_message(message):
	if message.from_user.id in admin_id:
		msg = bot.send_message(message.from_user.id, "Отправьте сообщение для отправки")
		bot.register_next_step_handler(msg, send_message_to_channel)
	else:
		bot.send_message(message.from_user.id, "Вы не являетесь администратором❌")

def global_dictionary(types, data, caption, method, login):
	if method == "add":
		if types == "text":
			get_data.append(types)
			get_data.append(data)
			get_data.append(method)
		else:
			get_data.append(types)
			get_data.append(data)
			get_data.append(caption)
			get_data.append(method)
	elif method == "clear":
		get_data.clear()
	elif method == "check":
		return get_data

def send_message_to_channel(message):
	if message.content_type == "text":
		global_dictionary("text", message.text, "", "add", message.from_user.id)
		bot.send_message(message.from_user.id, message.text, reply_markup = choice_keyboard)
	if message.content_type == "photo":
		global_dictionary("photo", message.photo[0].file_id, message.caption, "add", message.from_user.id)
		bot.send_photo(message.from_user.id, message.photo[0].file_id, caption = message.caption, reply_markup = choice_keyboard)


@bot.callback_query_handler(func = lambda call: True)
def iq_callback(call):
	if call.data == "choice_send":
		msg = global_dictionary("", "", "", "check", call.from_user.id)
		#Тут уже можно работать с msg
	elif call.data == "choice_clear":
		global_dictionary("", "", "", "clear", call.from_user.id)
bot.polling(none_stop = True, interval = 0)
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@qwwerty
CHANNEL_ID = 0  # Some ID


@bot.callback_query_handler(func=lambda call: True)
def iq_callback(call: types.CallbackQuery):
    if call.data == 'choice_clear':
        # Some code to clear
        return

    msg: types.Message = call.message

    if msg.content_type == 'text':
        bot.send_message(CHANNEL_ID, msg.text)
    elif msg.content_type == 'photo':
        bot.send_photo(CHANNEL_ID, msg.photo[0].file_id, msg.caption)
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
11 мая 2024, в 00:19
1000 руб./за проект
10 мая 2024, в 23:51
30000 руб./за проект
10 мая 2024, в 23:33
2500 руб./за проект