Y
Y
Yury Bondaruk2021-06-27 13:56:54
Python
Yury Bondaruk, 2021-06-27 13:56:54

Restarting a script after a crash?

Good afternoon. Faced such a problem that very often errors arrive with VKApi, as a result of which the bot breaks. At the same time, due to the presence of two cycles, doing while True: at the very beginning does not work, because the bot enters an infinite loop. How to make the bot restart automatically after a crash? Thanks in advance.

# -*- coding: utf-8 -*-

import vk_api
import vk 
import time
import json
import urllib.request
import requests

token = "-"
token_user = "-"

welcome = 
start = 

session = vk.Session(access_token=token_user)
api = vk.API(session ,v='5.92', lang='ru')

vk = vk_api.VkApi(token=token)

def get_button(label, color, payload=""):
    return {
        "action:": {
            "type": "text",
            "payload": json.dumps(payload),
            "label": label
        },
        "color": color
    }

keyboard = {
   "one_time": False,
   "buttons":[
      [
         {
            "action":{
               "type":"open_link",
               "label":"Перейти на сайт forblitz.ru",
               "link":"https://forblitz.ru/"
            },
         },
      ],
            [
         {
            "action":{
               "type":"open_link",
               "label":"Приложение ForBlitz для Android",
               "link":"https://forblitz.ru/app/"
            },
         },
      ],
                  [
         {
            "action":{
               "type":"text",
               "label":"Установка и удаление"
            },
            "color":"positive"
         },
         {
            "action":{
               "type":"text",
               "label":"Список модов"
            },
            "color":"secondary"
         }
      ],
                  [
         {
            "action":{
               "type":"text",
               "label":"Заказать мод"
            },
            "color":"secondary"
         },
         {
            "action":{
               "type":"text",
               "label":"Мод не работает"
            },
            "color":"secondary"
         }
      ],
            [
         {
            "action":{
               "type":"open_app",
               "app_id": 5748831,
               "label":"Рассылка",
               "owner_id":-116432643
                     },
         },
         {
            "action":{
               "type":"text",
               "label":"Позвать человека"
            },
            "color":"negative"
         }
      ],
        [       {
            "action":{
               "type":"text",
               "label":"Статус работы приложения и сайта",
                     },
            "color":"primary"
         },
   ]
   ]
}

keyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')
keyboard = str(keyboard.decode('utf-8'))

while True:
        messages = vk.method("messages.getConversations", {"offset": 0, "count": 20, "filter": "unanswered"}) #получение всех бесед бота
        if messages["count"] >= 1:
            id = messages["items"][0]["last_message"]["from_id"]
            body = messages["items"][0]["last_message"]["text"]
            if body == "Привет":
                vk.method("messages.send", {"peer_id": id, "message": welcome, "random_id": 0})
            elif body == "Начать":
                vk.method("messages.send", {"peer_id": id, "message": start, "keyboard": keyboard, "random_id": 0})
            elif body == "Установка и удаление":
                vk.method("messages.send", {"peer_id": id, "message": install_and_remove, "random_id": 0})
            elif body == "Список модов":
                vk.method("messages.send", {"peer_id": id, "message": mod_list, "random_id": 0})
            elif body == "Заказать мод":
                vk.method("messages.send", {"peer_id": id, "message": mod_order, "random_id": 0})
            elif body == "Мод не работает":
                vk.method("messages.send", {"peer_id": id, "message": mod_not_working, "random_id": 0})
            elif body == "Статус работы приложения и сайта":
                vk.method("messages.send", {"peer_id": id, "message": "Статус работы приложения указан в статусе сообщества и обновляется каждые 30 минут.", "random_id": 0})
            elif body == "Позвать человека":
                vk.method("messages.send", {"peer_id": id, "message": call_human, "random_id": 0})
        time.sleep(1) #задержка перед ответом бота (в секундах)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2021-06-27
@saboteur_kiev

use try correctly

4
4X_Pro, 2021-06-27
@XXXXPro

If the case is under Linux, then write the appropriate unit for systemd:

[Unit]
Description=Your Daemon
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service

[Service]
Restart=on-failure
RestartSec=10s

ExecStart=/usr/bin/python3  /path/to/script

Under Windows, you can also write the script as a service with the ability to restart in case of a crash. Well, as Saboteur
correctly noted above , so that the script does not crash from errors, you need to use try / except.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question