R
R
ruhgweg2021-12-10 15:06:13
Python
ruhgweg, 2021-12-10 15:06:13

Evaluate the code for writing my bot, if there is water in the code (something extra), then unsubscribe, and what are the forums that discuss topics of this kind?

here is the code for writing a VK bot in python (the basis, I did not finish it):

import vk_api, json
from vk_api.longpoll import VkLongPoll, VkEventType
from os.path import abspath
from key import token

vk_session = vk_api.VkApi(token = token)
longpoll = VkLongPoll(vk_session)

class User():
  def __init__(self, user_id, command, invested, balance, balance_investment):
    self.user_id = user_id
    self.command = command
    self.invested = invested
    self.balance = balance
    self.balance_investment = balance_investment

def save_bd(users):
  lines = []
  for user in users:
    lines.append(f'"user_id": {user.user_id}, "command": "{user.command}", "invested": {user.invested}, "balance": {user.balance}, "balance_investment": {user.balance_investment}')
  lines = "\n".join(lines)
  with open(f'{abspath(__file__)}/data.txt'.replace("\\", "/").replace("main.py/", ""), "w", encoding = "utf-8") as file:
    file.write(lines)
    file.close()

def read_bd():
  users = []
  with open(f'{abspath(__file__)}/data.txt'.replace("\\", "/").replace("main.py/", ""), "r", encoding = "utf-8") as file:
    lines = [x.replace("\n", "") for x in file.readlines()]
    file.close()
  for line in lines:
    line = eval("{" + line + "}")
    if line != "{}":
      users.append(User(user_id = line['user_id'], command = line['command'], invested = line['invested'], balance = line['balance'], balance_investment = line['balance_investment']))
  return users

def get_keyboard(text, color):
  return {
    "action": {
      "type": "text",
      "payload": "{\"button\": \"" + "1" + "\"}",
      "label": f'{text}'
    },
    "color": f'{color}'
  }

keyboard_main = {
  "one_time": False,
  "buttons": [
    [get_keyboard("Инвестировать", "positive")]
  ]
}

keyboard_back = {
  "one_time": False,
  "buttons": [
    [get_keyboard("Назад", "negative")]
  ]
}

keyboard_main = str(json.dumps(keyboard_main, ensure_ascii = False).encode("utf-8").decode("utf-8"))
keyboard_back = str(json.dumps(keyboard_back, ensure_ascii = False).encode("utf-8").decode("utf-8"))

def sender(user_id, message, keyboard):
  vk_session.method("messages.send", {"user_id": user_id, "message": message, "keyboard": keyboard, "random_id": 0})

users = read_bd()

print("Bot started!")
for event in longpoll.listen():
  if event.type == VkEventType.MESSAGE_NEW:
    if event.to_me:
      user_id = event.user_id
      message = event.message.lower()

      if message == "начать":
        flag = False
        for user in users:
          if user.user_id == user_id:
            flag = True
            break
        if not(flag):
          users.append(User(user_id = user_id, command = "main", invested = 0, balance = 100, balance_investment = 100))
          sender(user_id, " Ты попал в PassiveCapital. Наш бот поможет тебе заработать на нехилую старость. Погнали.", keyboard_main)
      else:
        for user in users:
          if user.user_id == user_id:
            if user.command == "main":
              if message == "инвестировать":
                sender(user_id, "1 = 1 рубль\n\nВы можете инвестировать: " + str(user.balance_investment + user.balance) + "\n\nБаланс который можно инвестировать: " + str(user.balance_investment) + "\nБаланс который можно вывести: " + str(user.balance) + "\n\nКакую сумму будете инвестировать?", keyboard_back)
                user.command = "investment"
      save_bd(users)

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