I
I
Igor_Merg2020-12-19 20:55:30
Python
Igor_Merg, 2020-12-19 20:55:30

Hello, there was an error while writing the bot?

The bottom line is that I need to write a bot so that he would take orders in PM and send them to the conversation.
That is, you need to use separately longpoll and botlongpoll.
I decided to try through the streams, but it gives such errors, please help

Error:

C:\Users\HP\Desktop\bot>python bot.py
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "bot.py", line 147, in beseda
    if pause_beseda == 1:
UnboundLocalError: local variable 'pause_beseda' referenced before assignment
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "bot.py", line 69, in ls_chat
    bd[id] = {'pause': pause,'nick': nick}
UnboundLocalError: local variable 'pause' referenced before assignment


Bot Code

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from vk_api.utils import get_random_id
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from threading import *
nick = None
pause = 0
pause_beseda = 0
bd = {}


#Клавиатуры ЛС бота
keyboard1 = VkKeyboard(one_time = True)
keyboard1.add_button('Заказать такси', color=VkKeyboardColor.POSITIVE)

def key_nick():
  keyboard2 = VkKeyboard(one_time = True)
  if nick is not None:
    keyboard2.add_button(nick, color=VkKeyboardColor.POSITIVE)
    keyboard2.add_line()
  keyboard2.add_button('Отменить заказ', color=VkKeyboardColor.NEGATIVE)
  return keyboard2

keyboard3 = VkKeyboard(one_time = True)
keyboard3.add_button('Отменить заказ', color=VkKeyboardColor.NEGATIVE)

#Клавиатуры беседы бота
keyboard4 = VkKeyboard(inline= True)
keyboard4.add_button('Взять заказ',color=VkKeyboardColor.POSITIVE)

keyboard5 = VkKeyboard(inline= True)
keyboard5.add_button('Отвез 150',color=VkKeyboardColor.POSITIVE)
keyboard5.add_button('Отвез 300',color=VkKeyboardColor.POSITIVE)
keyboard5.add_button('Отменить заказ',color=VkKeyboardColor.POSITIVE)
keyboard5.add_button('Закрыть заказ',color=VkKeyboardColor.POSITIVE)
#Код бота
def write_message(id, message):

  if sms == 1:
    authorize.method('messages.send',{'user_id': id, 'message': message, 'random_id': get_random_id(), 'keyboard': keyboard1.get_keyboard()})
  if sms == 2:
    authorize.method('messages.send',{'user_id': id, 'message': message, 'random_id': get_random_id(), 'keyboard': key_nick().get_keyboard()})
  if sms == 3:
    authorize.method('messages.send',{'user_id': id, 'message': message, 'random_id': get_random_id(), 'keyboard': keyboard3.get_keyboard()})
def write_chat(id, message):

  if sms_chat == 1:
    authorize.method('messages.send',{'chat_id': id2, 'message': message, 'random_id': get_random_id()})
  if sms_chat == 2:
    authorize.method('messages.send',{'chat_id': id2, 'message': message, 'random_id': get_random_id(), 'keyboard': key_nick().get_keyboard()})
  if sms_chat == 3:
    authorize.method('messages.send',{'chat_id': id2, 'message': message, 'random_id': get_random_id(), 'keyboard': keyboard3.get_keyboard()})

#Авторизация
authorize = vk_api.VkApi(token = '01dac92eb686dbc93f22fb7a7b403b3b855a302c43c67d8286d206394b6b680f5cac48ae38d83424c105e')
longpoll = VkLongPoll(authorize)
longpoll_chat = VkBotLongPoll(authorize, group_id = 201005383)

#Сообщения
def ls_chat():

  for event in longpoll.listen():
      if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
          reseived_message = event.text
          id = event.user_id
          #Проверка данных отдельного пользователя
          if id not in bd.keys():
              bd[id] = {'pause': pause,'nick': nick}
          
          pause = ((bd[id])['pause'])
          nick = ((bd[id])['nick'])

      # Заказ такси
          if pause == 0 and reseived_message == ('Заказать такси'):
              sms = 2
              write_message(id,'Цены по тарифу: 150 по городу, 350 за город.')
              write_message(id,'Введите ваш игровой ник или выбирите введенный ранее.')
              pause = 1
              ((bd[id])['pause']) = pause
          elif pause == 1:
              nick = event.text
              if nick == ('Отменить заказ'):
                  sms = 1
                  nick = None
                  write_message(id,'Заказ отменен.')
                  pause = 0
                  ((bd[id])['pause']) = pause
          
              else:
                  sms = 3
                  write_message(id,'Подробно опишите место откуда вас нужно забрать.')
                  ((bd[id])['nick']) = nick
                  pause = 2
                  ((bd[id])['pause']) = pause
          elif pause == 2:
              mesto = event.text
              if mesto == ('Отменить заказ'):
                  sms = 1
                  mesto = ''
                  write_message(id,'Заказ отменен.')
                  pause = 0
                  ((bd[id])['pause']) = pause
          
              else:
                  sms = 3
                  write_message(id,'Введите место, куда вам нужно приехать.')
                  mesto = event.text
                  pause = 3
                  ((bd[id])['pause']) = pause
          elif pause == 3:
              kuda = event.text
              if kuda == ('Отменить заказ'):
                  sms = 1
                  kuda = ''
                  write_message(id,'Заказ отменен.')
                  pause = 0
                  ((bd[id])['pause']) = pause
              else:
                  sms = 3
                  write_message(id,'Спасибо, что пользуетесь нашей компанией, ожидайте водителя...')
                  pause = 4
                  ((bd[id])['pause']) = pause
          elif pause == 4:
              ojidanue = event.text

              if ojidanue == ('Отменить заказ'):
                  sms = 1
                  ojidanue = ''
                  pause = 0
                  write_message(id,'Заказ отменен.')
                  ((bd[id])['pause']) = pause
              else:
                  sms = 3
                  write_message(id,'Вы уже сделали заказ, ожидайте принятия...')

          else:
              sms = 1
              write_message(id,'Хочешь заказать такси? Напиши "Заказать такси"')
def beseda():
  for event_beseda in longpoll_chat.listen():
      if event_beseda.type == VkBotEventType.MESSAGE_NEW and event_beseda.from_chat and event_beseda.message.get != '':
          reseived_message = event_beseda.message.get('text')
          id2 = event_beseda.chat_id
          nomer = 3123
          number = 'Заказ №: ', str(nomer)
          if pause_beseda == 1:
          	sms = 1
          	write_chat(id2,'Заказ №')
          	sms = 4
          	write_chat(id2,'Напишите "Взять заказ", что бы взять его.')
          	pause_beseda = 2
          elif pause_beseda == 2:
          	zakaz1 = event_beseda.message.get("text").lower()
          	if zakaz1 == 'взять заказ' or zakaz1 == '[club201005383|@vezet_province] взять заказ' :
            	write_chat(id2,number)
            	write_chat(id2, 'Если вы попали в ДТП или возникли личные проблемы, отмените заказ, пусть его возьмет другой таксист.')
            	write_chat(id2, 'После завершения заказа напишите "Отвез (сумма)"')
            	pause_beseda = 3
            	
            else:
            	pause_beseda == 1
          elif pause_beseda == 3:
          	zakaz2 = event_beseda.message.get('text').lower()
          	if zakaz2 == 'отменить заказ' or zakaz2	== '@vezet_province отменить заказ':
          		write_chat(id2, 'Вы отменили заказ.')
          else:
          	write_chat(id2,'?')

ls_chat_on = Thread(target = ls_chat)
beseda_on = Thread(target = beseda)

ls_chat_on.start()
beseda_on.start()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2020-12-19
@phaggi

If these variables

pause = 0
pause_beseda = 0

are not needed outside functions, then declare them inside functions before the first use.
If they are needed outside of functions ... I don’t know this VK of yours, is it possible to declare them global here? How safe is it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question