I am creating a bot that will ask users for api_id, api_hash, phone number and the code that came to this phone for authorization - aiogram

I am creating a bot that will ask users for api_id, api_hash, phone number and the code that came to this phone for authorization. After you have received everything, create a client to track messages that the user has written to any chats. I have two problems, the first is that it shows the error 400 PHONE_CODE_EMPTY, although the code is there, prints it through print, and the second problem is that it does not see the messages that the user writes, I will wait for any advice
class Data(StatesGroup):
api_id = State()
api_hash = State()
phone_number = State()
code = State()
auth_code = State()
#dp.message_handler(commands='start')
async def start(message):
await bot.send_message(message.chat.id, 'Начнём!')
# ID пользователя
user_id = message.from_user.id
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# вернуть список отдельных значений
conn.row_factory = lambda cursor, row: row[0]
# Позволяет делать SQL запросы
cur = conn.cursor()
# Проверка есть ли ID в БД
ids = cur.execute('SELECT user_id FROM users').fetchall()
print(ids)
for i in ids:
print(5)
if str(user_id) == str(i):
print(1)
await bot.send_message(message.chat.id, 'О, вы уже есть в нашей базе.\n'
'Необходимо авторизоваться!\n'
'Введите код...')
await Data.auth_code.set()
# Конец
await bot.send_message(message.chat.id, 'Теперь напиши magic в любой чат')
else:
print(4)
# Авторизация
await bot.send_message(message.chat.id, 'Чтобы я мог с вами работать, '
'нужно авторизоваться.\n'
'Вам нужно:\n'
'1. Перейти на сайт телеграмма https://my.telegram.org/auth и получить api_id и '
'api_hash\n'
'2. Отправить мне по очереди api_id и api_hash\n'
'3. Авторизоваться у меня по номеру телефона, чтобы '
'я мог сделать magic\n'
'Команды можно вызвать /commands')
# Конец
await bot.send_message(message.chat.id, 'Теперь напиши magic в любой чат')
#dp.message_handler(commands='commands')
async def commands(message):
await message.reply('/api_id - добавление/изменение api_id\n'
'/api_hash - добавление/изменение api_hash\n'
'/phone_number - добавление/изменение номера телефона\n'
'/code - отправить код для авторизации\n')
#dp.message_handler(commands='api_id')
async def api_id(message):
# Получение api_id
await Data.api_id.set()
await bot.send_message(message.chat.id, 'Жду api_id...')
#dp.message_handler(commands='api_hash')
async def api_id(message):
# Получение api_hash
await Data.api_hash.set()
await bot.send_message(message.chat.id, 'Жду api_hash...')
#dp.message_handler(commands='phone_number')
async def api_id(message):
# Получение phone_number
await Data.phone_number.set()
await bot.send_message(message.chat.id, 'Авторизация телефона.\n'
'Отправь мне свой номер телефона в международном формате, '
'т.е. с кодом(пример: +375295892123.\n')
await bot.send_message(message.chat.id, 'Жду номер телефона...')
"""Добавление user_id и api_id в БД
==================================================================================================="""
#dp.message_handler(state=Data.api_id)
async def api_id(message, state: FSMContext):
# ID пользователя
user_id = message.from_user.id
# api_id пользователя
api_id = message.text
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# Позволяет делать SQL запросы
cur = conn.cursor()
# Добавление данных
cur.execute("INSERT INTO users VALUES (?,?,?,?,?,?);",
(int(user_id), str(api_id), str(0), str(0), str(0), str(0)))
conn.commit()
cur.close()
await state.finish()
await bot.send_message(message.chat.id, 'Отлично теперь /api_hash')
"""Добавление api_hash в БД
==================================================================================================="""
#dp.message_handler(state=Data.api_hash)
async def api_hash(message, state: FSMContext):
# ID пользователя
user_id = message.from_user.id
# api_hash пользователя
api_hash = message.text
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# Позволяет делать SQL запросы
cur = conn.cursor()
# Добавление данных
cur.execute("UPDATE users set api_hash = ? WHERE user_id = ?", (str(api_hash), int(user_id)))
conn.commit()
cur.close()
await state.finish()
await bot.send_message(message.chat.id, 'Отлично теперь /phone_number')
"""Добавление phone_number в БД и отправление на номер смс с кодом
==================================================================================================="""
#dp.message_handler(state=Data.phone_number)
async def phone_number(message, state: FSMContext):
api_id = 11956109
api_hash = '2a767c96e93b1c4685aa11017818da52'
# ID пользователя
user_id = message.from_user.id
# api_hash пользователя
phone_number = message.text
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# Позволяет делать SQL запросы
cur = conn.cursor()
# Добавление данных
cur.execute("UPDATE users set phone_number = ? WHERE user_id = ?", (str(phone_number), int(user_id)))
conn.commit()
# Отправление на номер смс с кодом
results_api_id = cur.execute("SELECT api_id FROM users WHERE user_id = ?", (user_id,)).fetchone()
api_id = results_api_id[0]
results_api_hash = cur.execute("SELECT api_hash FROM users WHERE user_id = ?", (user_id,)).fetchone()
api_hash = results_api_hash[0]
print(api_id)
print(api_hash)
app = Client(f'code{user_id}', api_id, api_hash, phone_number, test_mode=True)
await app.connect()
sent_code = await app.send_code(phone_number)
print(sent_code)
cur.execute("UPDATE users set sent_code = ? WHERE user_id = ?", (str(sent_code), int(user_id)))
conn.commit()
await app.disconnect()
cur.close()
await state.finish()
await bot.send_message(message.chat.id, 'Жду кода...')
await Data.code.set()
#dp.message_handler(state=Data.code)
async def code(message, state: FSMContext):
code = message.text
user_id = message.from_user.id
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# Позволяет делать SQL запросы
cur = conn.cursor()
# Добавление данных
cur.execute("UPDATE users set code = ? WHERE user_id = ?", (str(code), int(user_id)))
conn.commit()
cur.close()
await state.finish()
await bot.send_message(message.chat.id, 'Отлично теперь я готов')
#dp.message_handler(commands='on')
async def m(message):
user_id = message.from_user.id
# Подключаемся к БД
conn = sqlite3.connect('data.db')
# Позволяет делать SQL запросы
cur = conn.cursor()
results_api_id = cur.execute("SELECT api_id FROM users WHERE user_id = ?", (user_id,)).fetchone()
api_id = results_api_id[0]
results_api_hash = cur.execute("SELECT api_hash FROM users WHERE user_id = ?", (user_id,)).fetchone()
api_hash = results_api_hash[0]
results_phone_number = cur.execute("SELECT phone_number FROM users WHERE user_id = ?", (user_id,)).fetchone()
phone_number = results_phone_number[0]
results_sent_code = cur.execute("SELECT sent_code FROM users WHERE user_id = ?", (user_id,)).fetchone()
sent_code = results_sent_code[0]
results_code = cur.execute("SELECT code FROM users WHERE user_id = ?", (user_id,)).fetchone()
code = results_code[0]
print(code)
await test(user_id, api_id, api_hash, phone_number, sent_code, message, code)
async def test(user_id, api_id, api_hash, phone_number, sent_code, message, code):
user = Client(f's{user_id}', api_id, api_hash, phone_number)
await user.connect()
signed = await user.sign_in(phone_number, sent_code, code)
print(signed)
if signed:
await message.reply('Подключено')
else:
await message.reply('Ошибка')
#user.add_handler(MessageHandler(msg, filters.me & filters.text))
#user.on_message(filters.me)
def qwe(client, message):
bot.send_message(message.chat.id, message.text)

Related

python-telegram-bot conversation-handler confustion

i'am new to python-telegram-bot library and i can't get this conversation handler do want i want!the first question always replace with /start or ... in result i tried to fix it but i couldn't i appratiate if you can help me with it.
this code ask several questions to user and at the end show the result but the result is not what i want and the final question was not even triged and i and very confiused! this is the code:
import logging
from telegram import ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import (Updater, CommandHandler,
MessageHandler, Filters, ConversationHandler)
import const
import ccxt
TELEGRAM_TOKEN = const.telegram_token()
B_API_KEY = const.binance_api_key()
B_SECRET_KEY = const.binance_secret_key()
exchange = ccxt.binance({
'apiKey': B_API_KEY,
'secret': B_SECRET_KEY,
})
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
QUESTION_1, QUESTION_2, QUESTION_3 ,QUESTION_4 ,QUESTION_5, QUESTION_6 , QUESTION_0 , QUESTION_7= range(8)
# Function to start the conversation handler
def start(update, context):
context.user_data['first_crypto'] = update.message.text
update.message.reply_text('Question 1:enter first crypto symbol (Ex: BNB): ')
return QUESTION_0
def question_second_crypto(update, context):
context.user_data['second_crypto'] = update.message.text
update.message.reply_text('Question 2:enter second crypto symbol (Ex: USD): ')
return QUESTION_1
def question_kind(update, context):
context.user_data['kind'] = update.message.text
update.message.reply_text('Question 3: what stategy? (long/short)')
return QUESTION_2
def question_leverage(update, context):
context.user_data['leverage'] = update.message.text
update.message.reply_text('Question 4: choose Leverage:')
return QUESTION_3
def question_entry_price(update, context):
context.user_data['entry_price'] = update.message.text
update.message.reply_text('Question 5: what is your entry price? (Ex: 300$): ')
return QUESTION_4
def question_targets(update, context):
context.user_data['targets'] = update.message.text
update.message.reply_text('Question 6: target to triger alert? (Ex: 310$):')
return QUESTION_5
def question_sl(update, context):
context.user_data['stop_loss'] = update.message.text
update.message.reply_text('Question 7: stop_loss (290$):')
return end(update, context)
def end(update, context):
first_crypto = context.user_data['first_crypto']
second_crypto = context.user_data['second_crypto']
leverage = context.user_data['leverage']
entry_price = context.user_data['entry_price']
targets = context.user_data['targets']
stop_loss = context.user_data['stop_loss']
update.message.reply_text(f'Your answers have been recorded:\n'
f'first_crypto: {first_crypto}\n'
f'second_crypto: {second_crypto}\n'
f'leverage: {leverage}\n'
f'entry price:{entry_price}\n'
f'targets:{targets}\n'
f'stop_loss:{stop_loss}')
return ConversationHandler.END
def main():
updater = Updater(TELEGRAM_TOKEN, use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
QUESTION_0: [MessageHandler(Filters.text, question_second_crypto)],
QUESTION_1: [MessageHandler(Filters.text, question_kind)],
QUESTION_2: [MessageHandler(Filters.text, question_leverage)],
QUESTION_3: [MessageHandler(Filters.text, question_entry_price)],
QUESTION_4: [MessageHandler(Filters.text, question_targets)],
QUESTION_5: [MessageHandler(Filters.text, question_sl)],
},
fallbacks=[MessageHandler(Filters.regex('^End$'), end)],
allow_reentry=True
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
the result was like this:
Your answers have been recorded:
first_crypto: /start
second_crypto: 1
leverage: 3
entry price:4
targets:5
stop_loss:6
the first_crypto: /start must be 1 and the stop_loss is never trigered.

KeyError: 'apikey'

This is what the code is but getting keyerror "apikey"
class Firebase:
""" Firebase Interface """
def init(self, config):
self.api_key = config["apikey"]
self.auth_domain = config["authDomain"]
self.database_url = config["databaseURL"]
self.storage_bucket = config["storageBucket"]
self.credentials = None
self.requests = requests.Session()
if config.get("serviceAccount"):
scopes = [
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/userinfo.email',
"https://www.googleapis.com/auth/cloud-platform"
]
service_account_type = type(config["serviceAccount"])
if service_account_type is str:
self.credentials = ServiceAccountCredentials.from_json_keyfile_name(config["serviceAccount"], scopes)
if service_account_type is dict:
self.credentials = ServiceAccountCredentials.from_json_keyfile_dict(config["serviceAccount"], scopes)
if is_appengine_sandbox():
# Fix error in standard GAE environment
# is releated to https://github.com/kennethreitz/requests/issues/3187
# ProtocolError('Connection aborted.', error(13, 'Permission denied'))
adapter = appengine.AppEngineAdapter(max_retries=3)
else:
adapter = requests.adapters.HTTPAdapter(max_retries=3)
for scheme in ('http://', 'https://'):
self.requests.mount(scheme, adapter)

asyncpg overwrite data in existing table

Rewriting code from sqlite to postgres.Encountered a connection problem. How to overwrite data?
async def get_coins_api_postgres():
conn = await asyncpg.connect(f'postgresql://{settings.user}:{settings.password}#{settings.host}/{settings.db_name}')
page = 0
coin_market = cg.get_coins_markets(vs_currency='usd', per_page=250, page=page)
df_market = pd.DataFrame(coin_market,columns=['market_cap_rank','id','name','current_price',"price_change_24h","price_change_percentage_24h",'market_cap',"market_cap_change_percentage_24h",'total_volume', "circulating_supply", "max_supply", "high_24h", "low_24h", ])
# df_market.to_sql('coins_info', conn, if_exists='replace')
tuples = list(df_market.itertuples(index=False, name=None))
s = await conn.copy_records_to_table('coins_info', records=tuples, columns=list(df_market), timeout=10)
# engine = create_engine('postgresql+psycopg2://postgres:{}#localhost:5432/coins'.format(settings.password))
# df_market.to_sql('coins_info', engine, if_exists='replace')
loop = asyncio.get_event_loop()
loop.run_until_complete(get_coins_api_postgres())
Just add after connection TRUNCATE. It works like drop but only data. Columns with their name remain.
async def get_coins_api_postgres():
conn = await asyncpg.connect(f'postgresql://{settings.user}:{settings.password}#{settings.host}/{settings.db_name}')
await conn.execute("TRUNCATE coins_info")
page = 0
coin_market = cg.get_coins_markets(vs_currency='usd', per_page=250, page=page)
df_market = pd.DataFrame(coin_market,columns=['market_cap_rank','id','name','current_price',"price_change_24h","price_change_percentage_24h",'market_cap',"market_cap_change_percentage_24h",'total_volume', "circulating_supply", "max_supply", "high_24h", "low_24h", ])
tuples = list(df_market.itertuples(index=False, name=None))
await conn.copy_records_to_table('coins_info', records=tuples, columns=list(df_market), timeout=10)
await conn.close()

Django | I'd like to delete a product and all of its related data from the database

I have a shopping cart with some items in it. If I delete a product from the basket, I also want to remove it from the ordered item. I am now unable to delete the order items and quantity. I am using ajax to remove items from the cart.
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
products = models.ManyToManyField(Product, blank=True)
subtotal = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2)
total = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = CartManager()
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
Quantity_Choices =(
('one', '1'),
('Two', '2'),
('Three', '3'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
quantity = models.CharField(max_length=22, choices=Quantity_Choices, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
class CartManager(models.Manager):
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = self.get_queryset().filter(id=cart_id)
if qs.count() ==1:
new_obj = False
cart_obj = qs.first()
if request.user.is_authenticated and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
else:
cart_obj = Cart.objects.new(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
def new(self, user=None):
user_obj = None
if user is not None:
if user.is_authenticated:
user_obj = user
return self.model.objects.create(user=user_obj)
The code for adding an item to the cart is as follows.
def cart_update(request):
product_id = request.POST.get('product_id')
print(product_id)
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("No product")
return render("cart_home")
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added= False
else:
cart_obj.products.add(product_obj)
added =True
request.session['cart_items'] = cart_obj.products.count()
if request.is_ajax():
print("ajax request")
json_data = {
"added":added,
"removed": not added,
"cartItemCount":cart_obj.products.count()
}
return JsonResponse(json_data)
return redirect("cart_home")
def productdetails(request, pk):
product = Product.objects.get(id=pk)
cart, cart_created= Cart.objects.get_or_create(request)
form =sizeForm(instance=product)
if request.method =='POST':
form = sizeForm(request.POST, instance =product)
if form.is_valid():
quantity=form.cleaned_data.get('quantity')
print(quantity)
orderitem, created = OrderItem.objects.get_or_create(product=product,cart=cart, quantity=quantity)
context= {
'object' : product,
'form':form
}
return render(request, 'home/productdetails.html', context)
orderitem
cart

Flask REST API TypeError

When i try to use on "/register" POST-body-raw {"name" : "mike", "password" : "demo"} in postman i get this bug, pls help to correct:
line 62, in signup_user
hashed_password = generate_password_hash(data['password'], method='sha256') TypeError: 'NoneType' object is not subscriptable
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import uuid
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Th1s1ss3cr3t'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///library.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.Integer)
name = db.Column(db.String(50))
password = db.Column(db.String(50))
admin = db.Column(db.Boolean)
class Authors(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
book = db.Column(db.String(20), unique=True, nullable=False)
country = db.Column(db.String(50), nullable=False)
booker_prize = db.Column(db.Boolean)
user_id = db.Column(db.Integer)
def token_required(f):
#wraps(f)
def decorator(*args, **kwargs):
token = None
if 'x-access-tokens' in request.headers:
token = request.headers['x-access-tokens']
if not token:
return jsonify({'message': 'a valid token is missing'})
try:
data = jwt.decode(token, app.config[SECRET_KEY])
current_user = Users.query.filter_by(public_id=data['public_id']).first()
except:
return jsonify({'message': 'token is invalid'})
return f(current_user, *args, **kwargs)
return decorator
#app.route('/register', methods=['GET', 'POST'])
def signup_user():
data = request.get_json()
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = Users(public_id=str(uuid.uuid4()), name=data['name'], password=hashed_password, admin=False)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'registered successfully'})
Most likely your request is missing content-type header.
Content-Type:application/json
In Postman you can set it in Headers tab. Another option is to select "raw" and "JSON (application/json)" in Body tab just above the text area.