N
N
Nikolai Getmanov2020-10-03 15:39:58
Python
Nikolai Getmanov, 2020-10-03 15:39:58

How to turn the string "2-2" into 0?

I am inventing a bot for VK that solves expressions. I enter messages 2-2 no answer. An error has occurred in Python.

Traceback (most recent call last):
File "G:\botd.py", line 21,
int_msg = int(msg)
ValueError: invalid literal for int() with base 10: '2-2'

import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from tok import main_token

vk_session = vk_api.VkApi(token='//API спрятан')
seesion_api = vk_session.get_api()
longpoll = VkLongPoll(vk_session)


def sender(id, text):
    vk_session.method('messages.send', {'user_id': id, 'message': text,
                      'random_id': 0})


for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.to_me:
            msg = event.text.lower()
            id = event.user_id
            if msg.isalpha() == False:
                int_msg = int(msg)
                sender(id, int_msg)
            else:
                sender(id, 'Пиши только буквы')


What can I do so that when I enter "2-2" the bot will answer "0"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-10-03
@sergey-gornostaev

from ast import literal_eval
...
result = literal_eval(msg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question