@Zalo1

Как привязать переменную к чату Telebot?

Можете подсказать, как создать переменную которая будет работать с каждым юзером отдельно?
import telebot
from telebot import types
import time
import random
global b
b = []
global a
a = []
global l
l = []
global op
op = []
p = 0
globalVar= {
  'chatid':{
  'track_title':0,
  'track_url': 'https://coolmusic.com/rep.wav',
  }
}

musicType = globalVar['chatid']['track_title']
musicUrl = globalVar['chatid']['track_url']

API_TOKEN = 'не скажу'

bot = telebot.TeleBot(API_TOKEN)


keyboard9 = telebot.types.ReplyKeyboardMarkup(True)
keyboard9.row('Готово')
keyboard9.row('1 Вопрос', '2 Вопрос','3 Вопрос')
keyboard9.row('4 Вопрос', '5 Вопрос')
keyboard80 = types.ReplyKeyboardMarkup(True, one_time_keyboard=True)
button_geo = types.KeyboardButton(text="Ваши Геоданные", request_location=True)
keyboard80.add(button_geo)
keyboard1 = types.ReplyKeyboardMarkup(True, one_time_keyboard=True)
button_phone = types.KeyboardButton(text="Авторизоваться", request_contact=True)
keyboard1.add(button_phone)
keyboard = telebot.types.InlineKeyboardMarkup()
callback_button = telebot.types.InlineKeyboardButton(text="Принять", callback_data="accept")
keyboard.add(callback_button)
keyboard2 = telebot.types.InlineKeyboardMarkup()
callback1_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes")
callback2_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no")
keyboard2.add(callback1_button, callback2_button)
keyboard3 = telebot.types.InlineKeyboardMarkup()
inline_1button = telebot.types.InlineKeyboardButton(text="Начать", callback_data="st1art")
keyboard3.add(inline_1button)
keyboard11 = telebot.types.InlineKeyboardMarkup()
callback3_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes1")
callback4_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no1")
keyboard11.add(callback1_button, callback2_button)
keyboard4 = telebot.types.InlineKeyboardMarkup()
callback5_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes2")
callback6_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no2")
keyboard4.add(callback1_button, callback2_button)
keyboard5 = telebot.types.InlineKeyboardMarkup()
callback7_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes3")
callback8_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no3")
keyboard5.add(callback1_button, callback2_button)
keyboard6 = telebot.types.InlineKeyboardMarkup()
callback9_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes4")
callback10_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no4")
keyboard6.add(callback1_button, callback2_button)
keyboard22 = telebot.types.InlineKeyboardMarkup()
callback12_button = telebot.types.InlineKeyboardButton(text="Товар 1", callback_data="tova1")
callback13_button = telebot.types.InlineKeyboardButton(text="Товар 2", callback_data="tova2")
callback14_button = telebot.types.InlineKeyboardButton(text="Товар 3", callback_data="tova3")
callback15_button = telebot.types.InlineKeyboardButton(text="Товар 4", callback_data="tova4")
callback16_button = telebot.types.InlineKeyboardButton(text="Товар 5", callback_data="tova5")
keyboard22.add(callback12_button, callback13_button, callback14_button, callback15_button, callback16_button)

keyboard23 = telebot.types.InlineKeyboardMarkup()
callback18_button = telebot.types.InlineKeyboardButton(text="Способ оплаты 1", callback_data="sposob1")
callback17_button = telebot.types.InlineKeyboardButton(text="Способ оплаты 2", callback_data="sposob2")
keyboard23.add(callback18_button, callback17_button)
keyboard88 = telebot.types.InlineKeyboardMarkup()
callback99_button = telebot.types.InlineKeyboardButton(text="Да", callback_data="yes22")
callback98_button = telebot.types.InlineKeyboardButton(text="Нет", callback_data="no22")
keyboard88.add(callback99_button, callback98_button)

keyboard12 = telebot.types.InlineKeyboardMarkup()
callback221_button = telebot.types.InlineKeyboardButton(text="Проверить статус", callback_data="check_status")
keyboard12.add(callback221_button)


def __init__(self, token, generator):
    self.updater = Updater(token=token)
    handler = MessageHandler(Filters.text | Filters.command, self.handle_message)
    self.updater.dispatcher.add_handler(handler)
    self.handlers = collections.defaultdict(generator)

def start(self):
    self.updater.start_polling()

@bot.message_handler(commands=['start'])
def send_welcome(message):
    musicType
    if musicType == 0:
        bot.send_message(chat_id=message.chat.id, text='Здравствуйте, вас приветствует VIP Bot. Пользовательское соглашение.', reply_markup=keyboard)
        print(message)
        global op
        op.append(str(message.from_user.username))
        global a
        a.append(str(message.from_user.username))
        print(a)
    else:
        bot.send_message(chat_id=message.chat.id,
                         text='Dас приветствует VIP Bot. Пользовательское соглашение.')


@bot.callback_query_handler(func=lambda call: True)
def qustions(call):
    global op
    if call.data == "accept":
        nomer = bot.send_message(chat_id=call.message.chat.id, text='Запрос номера.', reply_markup=keyboard1)
    elif call.data == "yes22":
        u = random.randint(0, 99999)
        u = str(u)
        bot.send_message(chat_id=call.message.chat.id, text='спасибо за обращение. Ваш номер запроса - #' + u, reply_markup=keyboard12)
        b.append(u)
    elif call.data == "tova1":
        doc = open('file.txt', 'a')
        doc.write("User and tovar - {tovar}\n".format(tovar='tovar 1 '+ str(op)))
    elif call.data == "tova2":
        doc = open('file.txt', 'a')
        doc.write("User and tovar - {tovar1}\n".format(tovar1='tovar 2 '+ str(op)))
    elif call.data == "tova3":
        doc = open('file.txt', 'a')
        doc.write("User and tovar3 - {tovar2}\n".format(tovar2='tovar 3 '+ str(op)))
    elif call.data == "tova4":
        doc = open('file.txt', 'a')
        doc.write("User and tovar4 - {tovar3}\n".format(tovar3='tovar 4 '+ str(op)))
    elif call.data == "tova5":
        doc = open('file.txt', 'a')
        doc.write("User and tovar5 - {tovar4}\n".format(tovar4='tovar 5 '+ str(op)))



def poka(message):
    bot.send_message(message.chat.id, 'Спасибо за обращение. Мы сяжемся с вами в ближайшее время.')

@bot.message_handler(content_types=['contact'])
def contact(message):
    if message.contact is not None:
        print(message.contact)
        a.append(message.contact.phone_number)
        doc = open('file.txt', 'a')
        doc.write("username and phone - {tele}\n".format(tele=a))
        print(a)
        bot.send_message(chat_id=message.chat.id, text='Чтобы продолжить, ответьте на пару вопросов.', reply_markup=keyboard9)
@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == '1 вопрос':
        bot.send_message(chat_id=message.chat.id, text='Что вас интересует:', reply_markup=keyboard22)
    elif message.text.lower() == '2 вопрос':
        bot.send_message(chat_id=message.chat.id, text='Выберите способ оплаты:', reply_markup=keyboard23)
    elif message.text.lower() == '4 вопрос':
        bot.send_message(chat_id=message.chat.id, text='Ваше данные:', reply_markup=keyboard9)
    elif message.text.lower() == '5 вопрос':
        bot.send_message(chat_id=message.chat.id, text='Ваш адрес:', reply_markup=keyboard80)
    elif message.text.lower() == 'готово':
        bot.send_message(chat_id=message.chat.id, text='Вы уверенны? Ваши ответы:'+'.', reply_markup=keyboard88)
    elif message.text.lower() == '3 вопрос':
         otvet = bot.send_message(chat_id=message.chat.id, text='Выберете дату и время доставки:', reply_markup=keyboard9)

@bot.message_handler(content_types=['text'])
def handel_message(message):
    bot.send_message(message.chat.id, "Вы написали: {0}".format(message.text))

@bot.message_handler(content_types=['location'])
def handle_loc(message):
    print(message.location)
    b.append(str(message.from_user.username))
    b.append(message.location.latitude)
    b.append(message.location.longitude)
    doc = open('file.txt', 'a')
    doc.write("location and userid. location v vodit v google. Primer:59.413074 53.6522- {location}\n".format(location=b))
    bot.send_message(chat_id=message.chat.id, text='Вы успешно отправили геопозицию', reply_markup=keyboard9)

bot.polling(none_stop=True)
  • Вопрос задан
  • 947 просмотров
Пригласить эксперта
Ответы на вопрос 1
@del4pp
у вас эта переменная уже есть :)
В каждого пользователя уникальный чатайди (message.chat.id)
Ее можно сохранять в базу данных (как и другую информацию о пользователе) и после этого написать функцию котораю будет работать в соответствии с нужными чат-айди так как вы только заходите
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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