How to get user ID through mentioning Telegram bot python - py-telegram-bot-api

I write code for Replit.com
i make a command /add_administrator that is, Ana must add the user ID of the user I mentioned to the file admins.json but after using the command the bot breaks What I understand the bot sees(/add_administrator)
(#user)ignore or not see
I would like to understand how to get the user id through a #mention
It will be in a different language full code :https://github.com/jonoto2/TeleBotPHP/blob/main/main.py
complete command code:
from webserver import keep_alive
import json
import random
import re
import os
import telebot
from telebot import types
#from telegram.ext import Updater
bot = telebot.TeleBot(os.environ['TOKEN'], parse_mode="HTML")
#bot.message_handler(commands=['add_adm'])
def add_adm(message):
# Check if user is admin
if is_admin(int(message.from_user.id)):
args = get_args(message.text)
# Check for args
if args and args[0].isdigit():
id = int(args[0])
with open('admins.json', "r") as jsonFile:
data = json.load(jsonFile)
if id not in data:
data.append(id)
with open("admins.json", "w") as jsonFile:
json.dump(data, jsonFile)
bot.reply_to(message, f"`{id}` Appointed as admin.")
else:
bot.reply_to(message,
'This user is already an administrator .')
else:
bot.reply_to(message, 'User is not found.')
else:
bot.reply_to(message, 'You are not an administrator .')
I have not tried anything because I do not understand how

Related

Why Selenium webdriver won't populate form

I've got some code that was intended to logon using selenium( selenium-4.7.2) so that I can keep up with job alerts on a popular job site. It's also a means of keeping my skills up while seeking work.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.service import Service
#from webdriver_manager.chrome import ChromeDriverManager
#driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set up the webdriver
driver = webdriver.Chrome()
# Navigate to the login page
driver.get('https://www.linkedin.com/uas/login')
# Enter your login credentials
driver.find_element_by_id('username').send_keys('elksie#gmail.com')
driver.find_element_by_id('password').send_keys('g')
# Click the "Sign in" button
driver.find_element_by_css_selector('button[type="submit"]').click()
# Wait for the page to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'jobs-search-box')))
# Navigate to the job search page
driver.get('https://www.linkedin.com/jobs/search/?currentJobId=3424225432&keywords=data%20analyst&refresh=true')
# Wait for the page to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'job-card-container')))
# Extract the job data
job_cards = driver.find_elements_by_class_name('job-card-container')
for job_card in job_cards:
title = job_card.find_element_by_class_name('job-card-container__title').text
company = job_card.find_element_by_class_name('job-card-container__subtitle').text
location = job_card.find_element_by_class_name('job-card-container__bullet').text
print(title, company, location)
# Close the browser
driver.close()
The lines...
driver.find_element_by_id('username').send_keys('elksie#gmail.com')
driver.find_element_by_id('password').send_keys('g')
errors with:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'
find_element_by_id has been deprecated. Use driver.find_element(By.ID, 'username')
Import By using:
from selenium.webdriver.common.by import By

FastAPI auth check before granting access to sub-applications

I am mounting a Flask app as a sub-application in my root FastAPI app, as explained in the documentation
Now I want to add an authentication layer using HTTPAuthorizationCredentials dependency, as nicely explained in this tutorial
tutorial code
How can I do that?
Preferably, I would like that any type of access attempt to my Flask sub-application goes first through a valid token authentication process implemented in my FastAPI root app. Is that possible?
You can use a custom WSGIMiddleware and authorize the call to flask app inside that like this:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask, escape, request
from starlette.routing import Mount
from starlette.types import Scope, Receive, Send
flask_app = Flask(__name__)
def authenticate(authorization: str = Header()):
# Add logic to authorize user
if authorization == "VALID_TOKEN":
return
else:
raise HTTPException(status_code=401, detail="Not Authorized")
class AuthWSGIMiddleware(WSGIMiddleware):
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
_, authorization = next((header for header in scope['headers'] if header[0] == b'authorization'), (b'authorization', "" ))
authenticate(authorization.decode('utf-8'))
await super().__call__(scope, receive, send)
routes = [
Mount("/v1", AuthWSGIMiddleware(flask_app)),
]
# OR Optionally use this as you were doing
# The above one is preferred as per starlette docs
# app.mount("/v1", WSGIMiddleware(flask_app))
#flask_app.route("/")
def flask_main():
name = request.args.get("name", "World")
return f"Hello, {escape(name)} from Flask!"
app = FastAPI(routes=routes, dependencies=[Depends(authenticate)])
#app.get("/v2")
def read_main():
return {"message": "Hello World"}
For the tutorial you are looking at, you can replace the invoking authenticate function in my example inside AuthWSGIMiddleware->__call__() with
AuthHandler().decode_toke(authorization)

clients = self.AVAILABLE_CLIENTS[name] KeyError: 'requests' flask authlib client

good day everybody,
having some issues with flask and authlib. Bellow snip of my flash code
from flask import Flask, render_template
from authlib.integrations.flask_client import OAuth
import os
app = Flask(__name__)
app._static_folder = os.path.abspath("static")
app.config.from_object('config')
oauth = OAuth(app)
webex = oauth.register(name='WEBEX', redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex', client_kwargs={
'scope': 'spark:all'
} )
config.py
import os
WEBEX_CLIENT_ID='C3a256be511cdf07e19f272960c44a214aec14b727b108e4f10bd124d31d2112c'
WEBEX_CLIENT_SECRET='secret'
WEBEX_ACCESS_TOKEN_URL='https://api.ciscospark.com/v1/access_token'
WEBEX_REDIRECT_URI='http://localhost:5000/AuthWebex'
WEBEX_SCOPE='spark:all'
when running above code I get the following error:
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/flask_client/oauth_registry.py", line 61, in register
self.use_oauth_clients()
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/_client/oauth_registry.py", line 49, in use_oauth_clients
clients = self.AVAILABLE_CLIENTS[name]
KeyError: 'requests'
looked at examples and did some research, no luck. Can't find any solution...
thanks in adv.
Tobi
UPDATE:
per comment bellow here the latest code:
from flask import Flask, render_template, url_for, request
from authlib.integrations.flask_client import OAuth
import os
import requests
app = Flask(__name__)
app._static_folder = os.path.abspath("static")
app.config.from_object('config')
app.secret_key = os.urandom(24)
oauth = OAuth(app)
oauth.register(
'webex',
api_base_url='https://api.ciscospark.com/v1',
authorize_url='https://api.ciscospark.com/v1/authorize',
access_token_url='https://api.ciscospark.com/v1/access_token',
redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex',
scope='spark:all')
#app.route('/')
def main():
"""Entry point; the view for the main page"""
return render_template('main.html')
#app.route('/authorize')
def authorize():
return render_template('authorize.html')
#app.route('/login')
def login():
#redirect_uri = url_for('AuthWebex', _external=True)
redirect_uri = 'http://webapp.dcloud.cisco.com:5000/AuthWebex'
print(redirect_uri)
return oauth.webex.authorize_redirect(redirect_uri)
#app.route('/AuthWebex')
def AuthWebex():
#print(request.__dict__)
token = oauth.webex.authorize_access_token( authorization_response=request.url,
redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex',
client_id='C3a256be511cdf07e19f272960c44a214aec14b727b108e4f10bd124d31d2112c',
client_secret='secret',
)
print("Token: ", token)
resp = oauth.webex.get('https://api.ciscospark.com/v1/people/me')
profile = resp.json()
print(profile)
# do something with the token and profile
return '<html><body><h1>Authenticated</h1></body></html>'
if __name__ == '__main__':
app.run()
oauth.webex.authorize_access_token function throws and error when called without the parameters. which is strange as most examples I found exactly do that.
client_id and client_secret are set via the config.py file. This works for the oauth.register function but not for the authorize_access_token.
Additional problem is that even with the parameters, it produces a valid token. When I call the get function I get the following error:
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/requests/models.py", line 317, in prepare
self.prepare_auth(auth, url)
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/requests/models.py", line 548, in prepare_auth
r = auth(self)
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 41, in __call__
raise UnsupportedTokenTypeError(description=description)
authlib.integrations._client.errors.UnsupportedTokenTypeError: unsupported_token_type: Unsupported token_type: 'token_type'
here is the format of the token returned from authorize_access_token function
Token: {'access_token': 'YWIzNGU3<secret>tNDQ5_PF84_7cc07dbd-<secret>-5877334424fd', 'expires_in': 1209599, 'refresh_token': 'MjU2ZDM4N2Et<secret>ZmItMTg5_PF84_7cc07dbd-<secret>877334424fd', 'refresh_token_expires_in': 7722014, 'expires_at': 1574863645}
went through the docs, the code on github and debugging in pycharm with no luck, help would be much appreciated!
The problem here is that this AuthWebex is not a standard OAuth service. The response has no token_type. We can fix it with Authlib compliance fix:
Check the example here:
https://docs.authlib.org/en/latest/client/frameworks.html#compliance-fix-for-oauth-2-0
The slack example has the same issue.

How to Fix unident does not match for any outer indentation level

i have tried to make a desktop assistant as voice recognizer and do as i say
but i get this error every time i try to run that: unindent does not match with any outer indentation level. can someone please help me!
it is somehow copied from YouTube video
gtts import gTTS
import speech_recognition as sr
import os
import webbrowser
import smtplib
def talktome(audio):
print(audio)
tts = gTTS(text=audio, lang='eng')
tts.save('audio.mp3')
os.system('mpg123 audio.mp3')
def myCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print('hello')
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration = 1)
audio = r.listen(source)
try:
command = r.recognize_google(audio)
print('you said: ' + command + '/n')
except sr.UnknownValueError:
assistant(myCommand())
return command
def assistant(command):
if 'open reddit python' in command:
chrome_pathchrome_path = '/Program Files (x86)/google/Chrome/Application/chrome.exe'
webbrowser.get(chrome_path).open(url)
if 'what\'s up' in command:
talkToMe('i am a bit busy')
if 'email' in command:
talkToMe('who is the recipient?')
recipient = myCommand()
if 'john' in recipient:
talkToMe('what should i say?')
content - myCommand()
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('username', 'password')
mail.sendmail('persion name', 'email address#whatever.com'. content)
mail.close()
talkToMe('email sent')
talkToMe('i am ready for your sound')
while true: assistant(myCommand())

Facebook API extend personal token

I'm currently using facebook GraphApi (imported with facepy) to build a crawler that extracts information from a group that is not mine. Since facebook's API v2.5 doesn't support extracting information from a group that is not mine, I'm forced to used an older version. My question is, how can I extend my personal token lifetime, taking into account that I can't create an app because it forces me to use the most recent API version. I'll drop the code below:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import facebook
from facepy import GraphAPI
from facepy import get_extended_access_token
import json
import schedule
import time
group_id = "the group id" #grupo operações stop coimbra https://www.facebook.com/groups/operacaostopcoimbra/
access_token = "access token i took from facebook developers"
class Crawler():
def __init__(self, access_token):
self._access_token = access_token
def crawl(self):
graph = GraphAPI(self._access_token) #aceder à GraphAPI
extended_token = get_extended_access_token(access_token, APP ID, APP SECRET) #PROBLEM IS HERE!
print extended_token
data = graph.get(group_id + "/feed", page=False, retry=3, limit=25)
data = self._parseJson(data)
return data
def _parseJson(self, data):
if data["data"][0]["message"]:
return data["data"][0]["from"]["name"] + " " + data["data"][0]["from"]["id"] + " " + data["data"][0]["message"]
else:
return None
result = Crawler(access_token)
schedule.every(1).minutes.do(result.crawl())
while 1:
schedule.run_pending()
time.sleep(1)
Seems like, no app, no token...