Error getting member: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: user not found - python

By the command /all, the bot must output the nicknames of all users of the group or channel, regardless of their rights. But it gives an error: Error getting member: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: user not found. To begin with, I used get_chat_administrators and gave out all the nicknames (of the added administrators) calmly. What could be the problem? I use bibl - pytelegrambotApi.
import telebot
TOKEN = "myTOKEN_ID"
bot = telebot.TeleBot(TOKEN)
#bot.message_handler(content_types=['text', 'photo', 'document', 'video', 'audio', 'location', 'contact', 'sticker'])
def handle_all_command(message):
if message.chat.type != "group" and message.chat.type != "supergroup":
return
if message.content_type == 'text' and '/all' in message.text.strip().split() or (message.content_type in ['photo', 'document', 'video', 'audio', 'location', 'contact', 'sticker'] and message.caption and '/all' in message.caption.strip().split()):
is_admin = False
bot_member = bot.get_chat_member(message.chat.id, bot.get_me().id)
if bot_member and bot_member.status == "administrator":
is_admin = True
if not is_admin:
bot.reply_to(message, "The bot is not configured!")
return
usernames = ""
members_count = bot.get_chat_members_count(message.chat.id)
for i in range(members_count):
#######################################
try:
user = bot.get_chat_member(message.chat.id, i+1)
if user.user.username:
usernames += "#" + user.user.username + " "
elif user.user.first_name:
usernames += user.user.first_name + " "
elif user.user.last_name:
usernames += user.user.last_name + " "
except Exception as e:
print("Error getting member: ", e)
#######################################
bot.reply_to(message, "Usernames: " + usernames)
bot.polling()
At first I used get_chat_administrators and gave out all nicknames calmly. What could be the problem?

Related

NameError in twilio API Python

im trying to run my code but it show "NameError: name 'message' is not defined
" but "message name is defined as shown in code" at ==> if init is True:
I'm just started api in python,
mport requests
from twilio.rest import Client
weather_id = []
API_KEY = "example"
account_sid = "AC123abc"
auth_token = "example"
client = Client(account_sid, auth_token)
para = {
"lat": 27.677904,
"lon": 78.230310,
"appid": API_KEY,
"exclude": "current, minutely, daily",
}
responced = requests.get(url="https://api.openweathermap.org/data/2.5/onecall", params=para)
responced.raise_for_status()
weather_data = responced.json()
holly_data = responced.json()["hourly"][:12]
for data in holly_data:
weather_res = data["weather"][0]["id"]
weather_id.append(weather_res)
init = False
for ids in weather_id:
if ids < 700:
init = True
if init is True:
message = client.messages.create(body="Weather Alert by S.P \n To you have a clear day \n Enjoy sir A.K.P \n "
"Thanks YOu",
from_="+19853042683",
to="+919354932229"
)
print(message.sid)
You need to set your init=False to init=True or add something like a
try:
print(message.sid)
except Exception as e:
print('Not initialized. Error: ', str(e))
so your script won't downright crash.
Also, never post your api_keys when you are a posting question.

Welcome Message isn't work because GetUpdates Telegram Bot API can't record joined notification update in supergroup

Few days ago i made a telegram bot with python using api from https://core.telegram.org/bots/api.
All the code works perfectly until i realize that the GetUpdates api didn't record the joined notification for the new user in my group
My plan is to made a welcome message to new user based on those record. The group not allowing user to send message (broadcast group) and right now i confused that i can't get any single record related to the new user joined, so then the welcome message didn't work perfectly
This is my function for getUpdates api and the welcome message
def get_updates(self, offset=0, timeout=50):
method = 'getUpdates'
params = {'timeout': timeout, 'offset': offset}
resp = requests.get(self.api_url + method, params)
result_json = resp.json()['result']
return result_json
def welcome_msg(self, item):
chat_id = item["message"]["chat"]["id"]
user_id = item["message"]["new_chat_member"]["id"]
if "username" in item["message"]["new_chat_member"]:
user_name = item["message"]["new_chat_member"].get("username", user_id)
else:
user_name = item["message"]["new_chat_member"].get("first_name", user_id)
welcom_msg = "HI WELCOME TO THIS GROUP"
to_url3 = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode=HTML&disable_web_page_preview=True'.format(token, chat_id, welcom_msg)
resp3 = requests.get(to_url3)
And after that the welcome message should be like this
new_offset = 1
all_updates = get_updates(new_offset)
if len(all_updates) > 0:
for current_update in all_updates:
first_update_id = current_update['update_id']
if old_id < first_update_id:
old_id = int(current_update['update_id'])
try:
if "new_chat_member" in current_update['message']:
welcome_msg(current_update)
chat_id = current_update["message"]["chat"]["id"]
message_id = current_update["message"]["message_id"]
new_offset = first_update_id + 1
except:
pass
Does the restriction of the group (member can't send message) made the getUpdates API couldn't work and the welcome message didn't showing up???
Go to botfather, bot settings and set privacy mode off for this bot, It should work

problem getting the token from my link to my token authentication function, what am i missing?

I'm trying to have a FORGOT PASSWORD? functionality in my website, I'm simply generating a token with a user id and then I send the form where they can update their password along with this token, but the problem is that I can't actually get that token after I click on the link, I get none, can someone tell me what I'm missing exactly? here's what I've done so far:
# generates the token with the user id
def get_reset_password_token(user_id, expires_in=1800):
return jwt.encode({'reset_password': user_id, 'exp': time() + expires_in},
app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
# verfies the token recovered from the link
def verify_reset_password_token(token):
try:
id = jwt.decode(token, app.config['SECRET_KEY'],algorithms=['HS256'])['reset_password']
except:
print("token was invalid.")
return None
return print("all good")
# sends email to the user containing reset password link
def send_password_reset_email(user_id, user_mail):
token = get_reset_password_token(user_id)
msg = Message('[El-menu] Password Reset Request', sender ='noreply#demo.com', recipients =[user_mail])
msg.body = f'''To reset your password, visit the following link:
{url_for('reset_password', token=token , _external=True)}
If you didn't make this request, ignore this email and no changes will be madeSincerely,
Sincerely,
El-menu Team
'''
mail.send(msg)
return print("email sent with token " + token +" to email " + user_mail, file=sys.stderr)
#app.route("/reset_password_request", methods = ["GET", "POST"])
def reset_password_request():
if request.method == "POST":
email = request.form.get("email")
# checks for valid mail
if not email:
error = "you must submit a valid email"
return render_template("reset_password_request.html", error = error)
# performs a query to find information about given email, whether it's in the system or not?
user = db.execute("SELECT * FROM users WHERE email= :email", email = email)
if user:
user_mail = user[0]['email']
user_id = user[0]['id']
send_password_reset_email(user_id, user_mail)
password_reset = "Password reset link has been sent to your email!"
return render_template("login.html", password_reset = password_reset)
else:
return render_template("reset_password_request.html")
#app.route('/reset_password/<token>', methods = ["GET", "POST"])
def reset_password(token):
if request.method == "POST":
print("trying to reset password now..", file=sys.stderr)
print(token, file=sys.stderr)
user_id = verify_reset_password_token(token)
print(user_id, file=sys.stderr)
if not user_id:
print("token is none", file=sys.stderr)
return redirect(url_for('index'))
print(user_id, file=sys.stderr)
password = request.form.get("password")
confirmation = request.form.get("confirmation")
# Ensure password was submitted
if not password:
error = "You must provide a password"
return render_template("reset_password.html", error = error)
# Ensure confirmation was submitted
elif not confirmation:
error = "You must provide a password confirmation"
return render_template("reset_password.html", error = error)
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d#$!#%*?&]{8,}$"
# compiling regex
pat = re.compile(reg)
# searching regex
mat = re.search(pat, password)
# validating conditions
if not mat:
error = "Password is weak"
return render_template("reset_password.html", error = error)
# Ensure Passwords match
if password != confirmation:
error = "Password and confirmation must match!"
return render_template("reset_password.html", error = error)
# Hash password
hashed_password = generate_password_hash(password)
db.execute("UPDATE users SET hash = :hash WHERE id = :id", hash = hashed_password, id = user_id)
return redirect("/")
else:
return render_template("reset_password.html")
I guess that's because the link you give {url_for('reset_password', token=token , _external=True)} in send_password_request_email makes a GET request so the user gets in reset_password and directly gets returned return render_template("reset_password.html")
You need to use render_template in order to render an email body that understands what token is.
So the first step would be to create an email template for the body of the email. The next step would be to use render_template and pass the token in.
Example from one of my Flask apps:
message = Message(
subject=render_template("email/reset_subject.txt"),
recipients=[user.email]
)
salt = current_app.config.get("SECURITY_PASSWORD_SALT", b"")
message.html = render_template(
"email/reset.html",
token=generate_code(user.email, salt=salt)
)
mail.send(message)

401 Authorization Required on Twitter API request

I'm building an Python script to automatically post status updates on Twitter. I've carefully read and followed the API documentation for creating a signature and do the request to update the status. But I'm getting an error when doing the request.
HTTP Error 401: Authorization Required
I've seen more questions like this on Stackoverflow and other resources, but couldn't find a solution to this problem yet.
def sendTweet(self):
url = 'https://api.twitter.com/1.1/statuses/update.json'
message = 'Testing'
oauths = [
['oauth_consumer_key', '1234567890'],
['oauth_nonce', self.generate_nonce()],
['oauth_signature', ''],
['oauth_signature_method', 'HMAC-SHA1'],
['oauth_timestamp', str(int(time.time()))],
['oauth_token', '1234567890'],
['oauth_version', '1.0']
]
signature = self.sign(oauths, message)
oauths[2][1] = signature
count = 0
auth = 'OAuth '
for oauth in oauths:
count = count + 1
if oauth[1]:
auth = auth + self.quote(oauth[0]) + '="' + self.quote(oauth[1]) + '"'
if count < len(oauths):
auth = auth + ', '
headers = {
'Authorization': auth,
'Content-Type': 'application/x-www-form-urlencoded'
}
payload = {'status' : message.encode('utf-8')}
req = urllib2.Request(url, data=urllib.urlencode(payload), headers=headers)
try:
response = urllib2.urlopen(req)
data = response.read()
print data
except (urllib2.HTTPError, urllib2.URLError) as err:
print err
This is what the self.sign function does
def sign(self, oauths, message):
signatureParams = ''
count = 0
values = [
['oauth_consumer_key', oauths[0][1]],
['oauth_nonce', oauths[1][1]],
['oauth_signature_method', oauths[3][1]],
['oauth_timestamp', oauths[4][1]],
['oauth_token', oauths[5][1]],
['oauth_version', oauths[6][1]],
['status', message]
]
customerSecret = '1234567890'
tokenSecret = '1234567890'
for value in oauths:
count = count + 1
signatureParams = signatureParams + self.quote(value[0]) + '=' + self.quote(value[1])
if count < len(oauths):
signatureParams = signatureParams + '&'
signature = 'POST&' + self.quote(self.endPoint) + '&' + self.quote(signatureParams)
signinKey = self.quote(customerSecret) + '&' + self.quote(tokenSecret)
signed = base64.b64encode(self.signRequest(signinKey, signature))
return signed
And below are the helper functions.
def generate_nonce(self):
return ''.join([str(random.randint(0, 9)) for i in range(8)])
def quote(self, param):
return urllib.quote(param.encode('utf8'), safe='')
def signRequest(self, key, raw):
from hashlib import sha1
import hmac
hashed = hmac.new(key, raw, sha1)
return hashed.digest().encode('base64').rstrip('\n')
This is what the auth string looks like when I print it.
OAuth oauth_consumer_key="1234567890",
oauth_nonce="78261149",
oauth_signature="akc2alpFWWdjbElZV2RCMmpGcDc0V1d1S1B3PQ%3D%3D",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="1540896473",
oauth_token="1234567890",
oauth_version="1.0"
That is exactly like it should be if I read the Twitter documentation. But still I get the 401 Authorization Required error.. I just can't see what is going wrong here.
The Access level for the keys is Read, write, and direct messages
All keys are replaced with 1234567890, but in the actual code I use the real ones.
Does someone have an idea what I am doing wrong? Thanks in advance!

Twilio/Django not receiving response SMS

I want to text a twilio number and start a series of questions for a user. If it is their first time texting, a new "Caller" should be created. If they have played before, I'd like to look up the "last_question", we asked them and ask them the appropriate question. My code below yields no SMS response and a Twilio error "HTTP retrieval failure."
In models.py I have
class Caller(models.Model):
body = models.CharField(max_length=200)
from_number = models.CharField(max_length=20)
last_question = models.CharField(max_length=2, default="0")
def __unicode__(self):
return self.body
In views.py
def hello_there(request):
body = request.REQUEST.get('Body', None)
from_number = request.REQUEST.get('From', None)
try:
caller = Caller.objects.get(from_number = from_number)
except Caller.DoesNotExist:
caller = None
if caller:
if caller.last_question == "0":
if body == "Password":
message = "Welcome to the game. What is 3 + 4?"
caller.last_question = "1"
else:
message = "What is the password?"
else:
message = "you broke me"
else:
new_caller = Caller(body=body, from_number=from_number, last_question="0")
new_caller.save()
message = "New user created"
resp = twilio.twiml.Reponse()
resp.sms(message)
return HttpResponse(str(resp))
Twilio employee here - the issue could be because you're not providing a csrf_exempt decorator around this view. Django will trigger a security error because it is receiving a HTTP POST request from twilio.com. Django will not accept any HTTP POST request without a csrf token unless you make it exempt.
Have you thought about using the django-twilio package for Django? It will make your life much easier when developing with twilio. This is what your view will look like with django-twilio:
from django_twilio.decorators import twilio_view
#twilio_view
def hello_there(request):
body = request.REQUEST.get('Body', None)
from_number = request.REQUEST.get('From', None)
try:
caller = Caller.objects.get(from_number=from_number)
except Caller.DoesNotExist:
caller = None
if caller:
if caller.last_question == "0":
if body == "Password":
message = "Welcome to the game. What is 3 + 4?"
caller.last_question = "1"
else:
message = "What is the password?"
else:
message = "you broke me"
else:
new_caller = Caller(body=body, from_number=from_number, last_question="0")
new_caller.save()
message = "New user created"
resp = twilio.twiml.Reponse()
resp.sms(message)
return resp
The twilio_view decorator will provide csrf exemption as well as ensuring all your requests are genuine and from twilio.com.
Check out the installation instructions to get started.

Categories

Resources