Skip to content
This repository has been archived by the owner on Jun 29, 2024. It is now read-only.

Commit

Permalink
added mongodb odn, added keyboard, added new commands
Browse files Browse the repository at this point in the history
  • Loading branch information
krax1337 committed Dec 26, 2019
1 parent 5a3914b commit ff4ce50
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 25 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
__pycache__/
.vscode/
venv/


src/config.py
3 changes: 2 additions & 1 deletion requirments.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
bs4==0.0.1
lxml==4.4.2
pyTelegramBotAPI==3.6.6
pyTelegramBotAPI==3.6.6
pymongo==3.10.0
15 changes: 8 additions & 7 deletions src/balance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import requests
from bs4 import BeautifulSoup as bs4


def getBalance(cardNumber):
"""
Return the balance of card
Expand All @@ -13,25 +14,25 @@ def getBalance(cardNumber):
r = session.get(url)
html_bytes = r.text
soup = bs4(html_bytes, 'lxml')
token = soup.find('input', {'name':'_token'})['value']
token = soup.find('input', {'name': '_token'})['value']

data = {
'cardNumber': cardNumber,
'_token': token,
}


r = session.post(url, data=data)
html_bytes = r.text
soup = bs4(html_bytes, 'lxml')
try:
cardNumber = soup.find('input', {'name':'CardNumber'})['value']
cardBalance = int(float(soup.find("span", style="color: #d23c3c;").text))
cardNumber = soup.find('input', {'name': 'CardNumber'})['value']
cardBalance = int(
float(soup.find("span", style="color: #d23c3c;").text))
except:
raise ValueError('Invalid card number')

return cardBalance

if __name__== "__main__":
print(getBalance(1001564614))

if __name__ == "__main__":
pass
106 changes: 92 additions & 14 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,106 @@
import config
import telebot
import balance
import utils
from telebot import types

bot = telebot.TeleBot(config.token)


@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):

bot.reply_to(message, "Введи номер своей карты, чтобы узнать текущий баланс")

@bot.message_handler(content_types=["text"])
def send_balance(message):

if len(str(message.text)) != 10 or not str(message.text).isdigit():
bot.send_message(message.chat.id, "Введи номер своей карты, чтобы узнать текущий баланс")
else:
regiter_user(message)

output = "/add чтобы добавить карту\n/status чтобы вывести баланс карт\n/help или /status чтобы вывести это сообщение"

bot.reply_to(message, output)


def regiter_user(message):
try:
utils.create_user_db(message.chat.id)
except:
pass


@bot.message_handler(commands=['echo'])
def send_echo(message):

this_message = str(message.text).split("/echo")[1].split(' ')[2]

bot.send_message(message.chat.id, "Ты написал мне {}".format(this_message))


@bot.message_handler(commands=['add'])
def add_card(message):

markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
markup.add('Отмена ❌')
chat_id = message.chat.id
msg = bot.send_message(
chat_id, 'Ввведите номер карты и имя (через пробел)', reply_markup=markup)
bot.register_next_step_handler(msg, check_card_number)


@bot.message_handler(commands=['status'])
def print_status(message):

chat_id = message.chat.id

cards = utils.update_balance(chat_id)

output = ''

for card in cards:
output += "Номер карты: " + str(card['card_number']) + "\n" + str(
card['card_name']) + " - " + str(card['balance']) + " тенге\n\n"

bot.send_message(
chat_id, output)


def check_card_number(message):
if "Отмена" in message.text:
bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
return

chat_id = message.chat.id
text = message.text

if text.split(' ', 1)[0].isdigit() and len(text.split(' ', 1)[0]) == 10 and len(text) > 10:
try:
balance.getBalance(text.split(' ', 1)[0])
except:
msg = bot.send_message(
message.chat.id, "Проверьте правильность введеного номера")
bot.register_next_step_handler(msg, check_card_number)
return

try:
balance_of_card = balance.getBalance(message.text)
bot.send_message(message.chat.id, "Ваш баланс равен {} тенге".format(balance_of_card))
text = text.split(' ', 1)
utils.add_card_db(chat_id, int(text[0]), text[1])
except:
bot.send_message(message.chat.id, "Проверьте правильность введеного номера")


msg = bot.send_message(chat_id, 'Такая карта уже существуеет.')
bot.register_next_step_handler(msg, check_card_number)
return

markup = types.ReplyKeyboardRemove()
msg = bot.send_message(
chat_id, 'Спасибо, карта сохранена.', reply_markup=markup)
else:
msg = bot.send_message(
chat_id, 'Номер карты состоит из 10 цифр, название может быть любым.\nНапример: 123456789 Карта Нурбека')
bot.register_next_step_handler(msg, check_card_number)
return


@bot.message_handler(content_types=["text"])
def send_balance(message):

bot.send_message(
message.chat.id, "Введи /help или /start, чтобы вывести список команд")


if __name__ == '__main__':
bot.infinity_polling()
bot.infinity_polling()
1 change: 0 additions & 1 deletion src/config.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
token = 'INSERT YOUR TOKEN'
72 changes: 72 additions & 0 deletions src/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from pymongo import MongoClient
import config
import balance

cluster = MongoClient(config.cluster)
db = cluster['astra-balance']


def create_user_db(chat_id):

collection = db["users"]

if collection.find_one({"chat_id": chat_id}) == None:
user = {
'chat_id': chat_id,
'notifications': 300,
}

collection.insert_one(user)
else:
raise ValueError('This user is already created')


def add_card_db(chat_id, card_number, card_name):
collection = db['users']

user = collection.find_one({'chat_id': chat_id})

card_exist = False

try:
for dicts in user['cards']:
for key, val in dicts.items():
if key == 'card_number' and val == card_number:
card_exist = True
except:
pass

if not card_exist:
collection.update_one(user, {"$push": {"cards":
{
'card_number': card_number,
'card_name': card_name.strip(),
'balance': balance.getBalance(card_number),
'notified': False,
}}
}, True)
else:
raise ValueError('This card is already added')


def update_balance(chat_id):

collection = db['users']
user = collection.find_one({"chat_id": chat_id})

for dicts in user['cards']:

current_balance = balance.getBalance(dicts['card_number'])

collection.update({'cards.card_number': dicts['card_number']}, {'$set': {
'cards.$.balance': current_balance,
}})

return user['cards']


if __name__ == "__main__":
# collection = db["users"]
# collection.delete_many({})

pass
1 change: 1 addition & 0 deletions start.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
echo "token = 'INSERT YOUR TOKEN'" > src/config.py
echo "cluster = 'mongodb://localhost:27017/'" >> src/config.py

python3 -m venv venv

Expand Down

0 comments on commit ff4ce50

Please sign in to comment.