1

The bot is working well when 1 person is using the bot. If, someone starts to use the bot, the dPoints Integer starts to mess up. This is a test, that helps people the get their depression level.

I have an idea. Maybe I can maybe different dPoints.py file for each person that starts to use the bot.

e.g. user1_dPoints, user2_dPoints, etc..

If you want to test my bot out, to see what is the problem - here is my telegram: @kmuradoff

Bot made using TeleBot

# imports
import sys
import time
import os
import config
import telebot
from telebot import types

# vars
dPoints = 0

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(commands = ['points'])
def showPoints(message):

    bot.send_message(message.chat.id, str(dPoints).format(
    message.from_user, bot.get_me()))

@bot.message_handler(commands=['start', 'help'])
def welcome(message):
    global dPoints
    dPoints = 0
    welcomeMarkup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    doTheTest = types.KeyboardButton("Начать тест")
    welcomeMarkup.add(doTheTest)
    bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!".format(
    message.from_user, bot.get_me()), reply_markup=welcomeMarkup)


@bot.message_handler(content_types=['text'])
def startingTest(message):

    UserName = message.from_user.first_name

    question0Heading = "----------- " + UserName + " -----------"

    question1Answer = "N/A"
    question2Answer = "N/A"
    question3Answer = "N/A"
    question4Answer = "N/A"
    question5Answer = "N/A"
    question6Answer = "N/A"
    question7Answer = "N/A"
    question8Answer = "N/A"
    question9Answer = "N/A"
    question10Answer = "N/A"
    question11Answer = "N/A"
    question12Answer = "N/A"
    question13Answer = "N/A"
    question14Answer = "N/A"
    question15Answer = "N/A"
    question16Answer = "N/A"
    question17Answer = "N/A"
    question18Answer = "N/A"
    question19Answer = "N/A"
    question20Answer = "N/A"

    q1 = types.ReplyKeyboardMarkup(row_width=1)
    q1s1 = types.KeyboardButton("Я не чувствую себя расстроенным, печальным.")
    q1s2 = types.KeyboardButton("Я расстроен")
    q1s3 = types.KeyboardButton("Я все время расстроен и не могу от этого отключиться.")
    q1s4 = types.KeyboardButton("Я настолько расстроен и несчастлив, что не могу это выдержать.")
    q1.add(q1s1, q1s2, q1s3, q1s4)

    q2 = types.ReplyKeyboardMarkup(row_width=1)
    q2s1 = types.KeyboardButton("Я не тревожусь о своем будущем.")
    q2s2 = types.KeyboardButton("Я чувствую, что озадачен будущим.")
    q2s3 = types.KeyboardButton("Я чувствую, что меня ничего не ждет в будущем.")
    q2s4 = types.KeyboardButton("Мое будущее безнадежно, и ничто не может измениться к лучшему.")
    q2.add(q2s1, q2s2, q2s3, q2s4)

    q3 = types.ReplyKeyboardMarkup(row_width=1)
    q3s1 = types.KeyboardButton("Я не чувствую себя неудачником.")
    q3s2 = types.KeyboardButton("Я чувствую, что терпел больше неудач, чем другие люди.")
    q3s3 = types.KeyboardButton("Когда я оглядываюсь на свою жизнь, я вижу в ней много неудач.")
    q3s4 = types.KeyboardButton("Я чувствую, что как личность я - полный неудачник.")
    q3.add(q3s1, q3s2, q3s3, q3s4)
    
    while message.text == str(q21s1.text) or str(q21s2.text) or str(q21s3.text) or str(q21s4.text):
        if message.chat.type == "private":
            global dPoints
            if message.text == "Начать тест":
                markup = telebot.types.ReplyKeyboardRemove()
                bot.send_message(message.chat.id, "ИНСТРУКЦИЯ".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(1.5)
                bot.send_message(message.chat.id, "Группа #1".format(
                message.from_user, bot.get_me()), reply_markup=q1)
                break
            elif message.text == str(q1s1.text) or message.text == str(q1s2.text) or message.text == str(q1s3.text) or message.text == str(q1s4.text):
                if message.text == str(q1s1.text):
                    dPoints = dPoints + 0
                elif message.text == str(q1s2.text):
                    dPoints = dPoints + 1
                elif message.text == str(q1s3.text):
                    dPoints = dPoints + 2
                elif message.text == str(q1s4.text):
                    dPoints = dPoints + 3
                markup = telebot.types.ReplyKeyboardRemove()
                time.sleep(1)
                bot.send_message(message.chat.id, "Вы ответили на 1 из 21 вопросов".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(2)
                bot.send_message(message.chat.id, "Группа #2".format(
                message.from_user, bot.get_me()), reply_markup=q2)
                break

            elif message.text == str(q2s1.text) or message.text == str(q2s2.text) or message.text == str(q2s3.text) or message.text == str(q2s4.text):
                if message.text == str(q2s1.text):
                    dPoints = dPoints + 0
                elif message.text == str(q2s2.text):
                    dPoints = dPoints + 1
                elif message.text == str(q2s3.text):
                    dPoints = dPoints + 2
                elif message.text == str(q2s4.text):
                    dPoints = dPoints + 3
                markup = telebot.types.ReplyKeyboardRemove()
                time.sleep(1)
                bot.send_message(message.chat.id, "Вы ответили на 2 из 21 вопросов".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(2)
                bot.send_message(message.chat.id, "Группа #3".format(
                message.from_user, bot.get_me()), reply_markup=q3)
                break



print("Bot Started Successfully")

bot.polling(none_stop=True)
wowkin2
  • 5,895
  • 5
  • 23
  • 66
Kamal Muradov
  • 49
  • 1
  • 1
  • 10
  • 2
    First rule of the multi-user club: no `global`. – Klaus D. Aug 15 '20 at 16:24
  • @KlausD. So what do i do now? Can you help me please?) – Kamal Muradov Aug 15 '20 at 16:30
  • 1
    Rewrite your code to not use globals. You could have a dictionary that stores user related information per user. (fun fact: dictionaries don't need `global`) The next step in evolution would be object oriented programming. – Klaus D. Aug 15 '20 at 16:38
  • @KlausD. Can you show me what i probably must do. Can show me the code, how it must look like, thanks! – Kamal Muradov Aug 15 '20 at 16:50
  • I will happily tell which direction to walk, but I'm not going to carry you. – Klaus D. Aug 15 '20 at 17:57
  • @KlausD. yes, please – Kamal Muradov Aug 15 '20 at 18:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219878/discussion-between-kamal-muradov-and-klaus-d). – Kamal Muradov Aug 15 '20 at 18:16
  • you need `message.text == str(...) or message.text == str(...) or message.text == str(...)` or use `message.text in (str(...), str(....), str(...) )`. – furas Aug 15 '20 at 19:19
  • if `q1s1.text` is a string then you don't need `str()` to convert string to the same string. – furas Aug 15 '20 at 19:21
  • if you have to work with many users or values then better use dictionary like `dPoints[user.id] = ...`. The same you could do with other values - like `question1Answer[user.id] = ...`. You could even use dictionary or list to keep answers `question[user.id][1]` instead of `question1Answer[user.id]`, `question[user.id][2]` instead of `question2Answer[user.id]`, etc. – furas Aug 15 '20 at 19:24
  • @furas can you help me with this please? I am just a beginner. Contact me in telegram: kmuradoff – Kamal Muradov Aug 15 '20 at 21:58

1 Answers1

0

As you can see from example in GitHub repository of TeleBot library, they propose to use user_dict with values per chat_id. You can do the same.

What else I'd suggest, to use default_dict.


# YOUR IMPORTS HERE
from collections import defaultdict


import config
import telebot
from telebot import types


bot = telebot.TeleBot(config.TOKEN)

# dict that will store all information per chat
user_info = defaultdict(dict)


# Show current amount of points to user
@bot.message_handler(commands = ['points'])
def show_points(message):
    d_points = user_info[message.chat.id].get('d_points', 0)

    bot.send_message(message.chat.id, 'You have {} d_points'.format(d_points).format(message.from_user, bot.get_me()))


# You method where value should be changed
@bot.message_handler(content_types=['text'])
def message_method(message):
    points = 3
    d_points = user_info[message.chat.id].get('d_points', 0)
    user_info[message.chat.id] = d_points + points

    bot.send_message(message.chat.id, 'Now you have: {} d_points'.format(d_points).format(message.from_user, bot.get_me()))

wowkin2
  • 5,895
  • 5
  • 23
  • 66