A
A
Arthur2018-07-10 16:50:06
Python
Arthur, 2018-07-10 16:50:06

Defining conversations python bot vk_api. How to implement the definition of conversations for the vk_api longpoll bot?

Hello everyone. I have a question about creating a VK bot. All requests are accepted normally, but there is another problem. The bottom line is that the bot will work with 50 conversations or more, but I still have a work implementation with only 1 conversation at least. You need to come up with an algorithm so that he was able to define requests and work with conversations SEPARATELY. How it works now:
1:user writes /start -- bot starts
2; user writes /info - data is written (from where/where/status/price and then to database)
3:bot terminates and that's it
What happens when it works with multiple conversations:
1: person from first conversation writes /start == he started
2: person from conversation number 2 can no longer use /start as it is enabled in conversation number one
3: a person from conversation number 2 writes the start at home, but conversation number one turns off the bot.
There is such a problem now. I will attach the code for this

def acc_work():
  день – 3.
    long = vk.method('messages.getLongPollServer', {'need_pts':1, 'Ip_version':3})
    while 1:
        #проверка на входящие сообщения. Порой случаются моменты, когда некоторые сообщения лонг не ловит, чаще из-за сбоев или отключения.
        old_messages = check_mess()
        response = requests.get('https://{server}?act=a_check&key={key}&ts={ts}&wait=90&mode=2&version=2'.format(server=long['server'], key=long['key'], ts=long['ts'])).json()
        if 'updates' in response:
            messages = old_messages #Далее формируем список, в который будет входить информация о запросах.
            for z in range(len(response['updates'])):
                if response['updates'][z][0] == 4:
                    summands = []
                    flag = response['updates'][z][2]

     

                    for number in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 65536]:  # проходим циклом по возможным слагаемым
                        if flag & number:  # проверяем, является ли число слагаемым с помощью побитового И
                            summands.append(number)  # если является, добавляем его в массив
                    if 2 not in summands: #если это не исходящее от бота сообщение:
                        user_id = response['updates'][z][3]
                        message = response['updates'][z][5]
                        user_flag = False
                        return response['updates'][z]

        try:
            long['ts'] = response['ts']
        except:
            long = vk.method('messages.getLongPollServer', {'need_pts': 1, 'Ip_version': 3})




def mult(test):
    precent = (test*4)/100
    price = precent+test
    return price




def info_func(q):
    q = 0
    a = acc_work()
    infom = ['/info','\info','/Info','/data','/данные']
    ok = ['/Yes','/yes','\Yes','\yes']
    nok = ['/No','/no']
    if a[5] in infom:
        print("часть инфо,началась запись ")
        createanswer(a)
        IFgroup(a, "ВВедите Откуда")


        x = ''
        while x !=False :
            if len(x) == 7 and x[5].startswith("#"):
                massive = ["Откуда","Куда","Состояние","Цена и шип","Карта продавца"]
                z = x[5][1:].split("#")
                while len(z)<2:
                    for i in  massive[1:]:
                            formal = "Введите " + i + '\n'+"Введите '/stop' если данные неверны и запустите команду /start снова"
                            if i == "Цена и шип":
                                formal =  "Введите " + i + \
                                '\n'+"Введите '/stop' если данные неверны и запустите команду /start снова" + '\n' + "введите только числа со знаком #"
                                IFgroup(x,formal)
                                check = acc_work()[5]
                            else:
                                IFgroup(x,formal)
                                check = acc_work()[5]
                            while check.startswith("#")==False:
                                stop =['/stop','\stop','\Stop','/Stop']
                                if check in stop:
                                    IFgroup(x,"Выход из заполнения")
                                    return 0
                                else:
                                    check = acc_work()[5]
                            else:
                                z.append(check[1:])
                else:
                    if len(z) >2:
                        x[5] = "accept"
                        accept = x
                        historyMessage(x,z[::-1])
                        createanswer(accept)

                        IFgroup(x,"ВВeдите '/Yes' или'/No'")
                        x = acc_work()

            elif len(x) == 7 and x[5] in nok:
                IFgroup(x,"Окей,напишите  еще раз '/start' если нужно запустить бота еще раз")
                z.clear()
                return 0

            elif len(x) == 7 and x[5] in ok:
                z.append(random.randint(1,10000))
                pass1= z.append(randomsPASS())
                file = ["Откуда,Куда,Состояние,Цена,Карта продавца,ID,PASS".split(","),
                        z]
                my_list = []
                fieldnames = file[0]
                for values in file[1:]:
                    inner_dict = dict(zip(fieldnames, values))
                    my_list.append(inner_dict)
                surname(my_list, fieldnames)
                shutil.copy("test1.csv", "copyTest1.csv")

                price1 = mult(int(z[3]))
                IFgroup(x,"Итого "+ str(price1)+"руб"+
                        "\n"+"Ваш ID"+str(z[5])+"\n"+
                        "Ждем оплаты: "+
                        '\n'+'00000000000000')
                

                print(x)
                id = acc_work()

                while id[3] != 12345 and id[5]!=('/go'+str(int(price1))):
                    id = acc_work()
                else:
                    IFgroup(x, "Деньги получены")
                    return 1



            elif len(x)==7 and x[5] == '/stop':
                IFgroup(x,"Выход из заполнения")
                return 0

            else:
                x = acc_work()





















def start():
    var = acc_work()
    print(var)
    keys = ['помощь',"/help","Помощь"]
    start = ['/start','/Start','\start','\Start','/tovar','/Tovar']

    #while (var[5]  in start or var[5] in keys);

    if (var[5] in start or var[5] in keys):
        time.sleep(5)
        createanswer(var)
        while (var[3] -  200000000):
            info_func(1)



       


Порой бывают исключения в сообщениях, их можно решать
. Ну ты поймешь.
while 1:
    try:
      
       start()
      

    except:
        print(traceback.format_exc()) 
        time.sleep(7)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question