telethon how to request call with code for login - telethon

Since I am writing a client, my friends from the USA noticed that the code does not go through SMS, but only through a call. but I don’t understand how to do it, how to request a call(
await client.connect()
code_settings = types.CodeSettings(
current_number=True,
allow_flashcall=False,
allow_app_hash=False
)
result = await client(functions.auth.SendCodeRequest(
phone_number=phone,
api_id=api_id,
api_hash=api_hash,
settings=code_settings
))
# time.sleep(10)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# time.sleep(20)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# result = await client(SentCodeTypeCall(5))
# result = await client(functions.auth.)
while not isinstance(result.type, SentCodeTypeCall):
# time.sleep(10)
result = await client(functions.auth.ResendCodeRequest(
phone_number=phone,
phone_code_hash=result.phone_code_hash
))
# time.sleep(20)
# await client(functions.auth.SendCodeRequest(
# phone_number=phone,
# api_id=api_id,
# api_hash=api_hash,
# settings=code_settings
# ))
def code_callback():
code = input('Please enter the code you received: ')
return code
time.sleep(5)
await client.start(phone=phone, code_callback=code_callback)
I assume this is not the correct code.
can I tell the SendCode Request method to call immediately without sending SMS?

Related

telethon :A wait of 16480 seconds is required (caused by ResolveUsernameRequest)

i'm trying to use telethon to send messages to telegram groups. after some times runing, it reruens:
A wait of 16480 seconds is required (caused by ResolveUsernameRequest).
the code is:
async def main():
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
config = configparser.ConfigParser()
config.read("seetings.ini",encoding= 'utf-8')
message = config['Customer']['message']
internal = config['Customer']['internal']
count = 0
excel_data = pandas.read_excel('tg_groups.xlsx', sheet_name='Groups')
for column in excel_data['GroupUsername'].tolist():
try:
if str(excel_data['GroupUsername'][count]) == 'None':
count += 1
continue
else:
chat = await client.get_input_entity(str(excel_data['GroGroupUsernameupID'][count]))
await client.send_message(entity=chat, message=message)
except Exception as e:
print(e)
time.sleep(int(internal))
count = count + 1
continue
time.sleep(int(internal))
count = count + 1
if __name__ == '__main__':
if proxytype == 'HTTP':
print('HTTP')
client = TelegramClient('phone'+phone, api_id, api_hash, proxy=(socks.HTTP, 'localhost', int(proxyport))).start()
if proxytype == 'socks5':
print('SOCKS5')
client = TelegramClient('phone'+phone, api_id, api_hash, proxy=(socks.SCOKS5, 'localhost', int(proxyport))).start()
myself = client.get_me()
print(myself)
freqm = config['Customer']['freq']
print(int(freqm))
while True:
with client:
client.loop.run_until_complete(main())
time.sleep(int(freqm))`
`
from the 'Entity' guide, it says get_input_entity method will search the user info from session file cache, why it it still call the 'ResolveUsernameRequest'to get the user info? anything i missed?
thanks for any advice.
'Entity' guide, it says get_input_entity method will search the user info from session file cache, why it it still call the 'ResolveUsernameRequest'to get the user info? anything i missed or the session file didn't keep the user info cache?

the post sent by the bot telegram is not deleted for all users

I have a function which allows to send a message to all users who clicked the start button.
#dp.message_handler(commands=['Yes'], state=Post.send_post)
async def process_name(message: Message, state: FSMContext):
for admin in admins:
if message.from_user.id == admin:
async with state.proxy() as data:
data['send_post'] = message.text
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
await state.finish()
print(result)
try:
for z in range(len(result)):
print(result[z][0])
await dp.bot.send_photo(chat_id=result[z][0], photo=data['photo'], caption=data['CAPTHION'], reply_markup=kb)
print(z)
test = message.message_id + 1
await dp.bot.send_message(chat_id=result[z][0], text=f'id поста {test}')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
Also, there is a function that allows you to delete messages by id. The administrator enters the deleted command, after which the bot asks to enter its id. When the Administrator enters an id, the bot deletes messages through a loop, iterating over the id. But for some reason, it only deletes a post from one user, then it throws an error
aiogram.utils.exceptions.MessageToDeleteNotFound: Message to delete not found
Please help me I can't figure out why
#dp.message_handler(commands=['deleted'], state=None)
async def send_id(message: Message):
for admin in admins:
if message.from_user.id == admin:
await Post.Sen_id.set()
await dp.bot.send_message(chat_id=admin, text='Введите ID поста, который нужно удалить.')
await Post.next()
#dp.message_handler(state=Post.del_mess)
async def deleted_post(message: Message, state: FSMContext):
for admin in admins:
if message.from_user.id == admin:
async with state.proxy() as data:
data['sen_id'] = message.text
try:
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
#message_ids = int(data['sen_id'])
for z in range(len(result)):
print('/////////////deleted/////////////')
print(result)
print(z)
await dp.bot.delete_message(chat_id=result[z][0], message_id=data['sen_id'])
print('Сообщение удалено')
#chat_id = message.chat.id
#await dp.bot.delete_message(message.chat.id, message_ids)
await dp.bot.send_message(chat_id=admin, text='пост удален')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
This is a code that does what you wish for - deleting message with given message_id in every chat where that message exist. Later I'll explain why this is actually not a good solution.
The problem is with the placing of the try-except block. In your code, if deleting the message fails for a single user, for all users that are past him in the database the deletion will not be even attempted. Solution would be to place the try-except block in the for loop.
...
if message.from_user.id == admin:
async with state.proxy() as data:
data['sen_id'] = message.text
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
#message_ids = int(data['sen_id'])
for z in range(len(result)):
try:
print('/////////////deleted/////////////')
print(result)
print(z)
await dp.bot.delete_message(chat_id=result[z][0], message_id=data['sen_id'])
print('Сообщение удалено')
#chat_id = message.chat.id
#await dp.bot.delete_message(message.chat.id, message_ids)
await dp.bot.send_message(chat_id=admin, text='пост удален')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
except Exception as e:
print(e)
...
However, after testing this approach, I believe you will realise that there is a problem: if you send a "post" to multiple users, it may have a different message_id for different users! So you would have to use a different approach.

How to enable TLS on a socket created with asyncio.start_server

I created a server in python using asyncio.start_server but what I want is to enable TLS for this server after its creation. I know it's possible to enable TLS using the tls parameter when creating the server but I want to do it later in the code.
I saw How do I enable TLS on an already connected Python asyncio stream?, it doesn't help me understand what to do.
Thank you for your kind answer and your time reading this.
The code for the server :
# ..init some parameters for the server
async def start_tls_connection(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter):
global ID
global msgList
global onlineList
global socket_server
data = await PStream.read_from_stream(streamObject=client_reader, debugMessage='Got message from client :')
if data == None:
return -1 # Handshake failure
# before proceeding we must upgrade the socket of the server to one that enables tls :
context = get_context()
logging.debug('socket before = ' + str(socket_server.sockets[0]._sock))
logging.debug(str(context))
socket_server.sockets[0]._sock = context.wrap_socket(socket_server.sockets[0]._sock)
logging.debug('socket after = ' + str(ssl_sock))
# upgrade socket here
data = await PStream.write_from_stream(streamObject=client_writer,
msg='<proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>',
debugMessage='Answer sent from server :')
if data == '':
return -1 # Handshake failure
# waiting for client to send a new stream header
data = await PStream.read_from_stream(streamObject=client_reader, debugMessage='Got message from client :')
if data == None:
return -1 # Handshake failure
# ... others methods for handshake
async def on_connect_client(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter):
logging.debug("START OF HANDSHAKE\nFIRST STEP: STREAM SESSION")
res = await stream_init(client_reader, client_writer)
if res == -1:
return res
logging.debug("START OF TLS HANDSHAKE")
res = await start_tls_connection(client_reader, client_writer)
if res == -1:
return res
logging.debug("START OF AUTHENTIFICATION")
res = await handshake_auth(client_reader, client_writer)
if res == -1:
return res
logging.debug("START OF ROOSTER PRESENCE")
res = await handshake_rooster_presence(client_reader, client_writer)
if res == -1:
return res
logging.debug("Waiting for request...")
while True:
data = await PStream.read_from_stream(streamObject=client_reader, debugMessage='Got message from client :')
if data == None:
break
async def server_start():
global socket_server
socket_server = await asyncio.start_server(on_connect_client, IP, PORT) # tls=ssl_context not here yet
logging.debug("Server just started")
async with socket_server:
await asyncio.gather(socket_server.serve_forever())
if __name__ == '__main__':
try:
asyncio.run(server_start())
except Exception as e:
print("Exception: ", str(e))
The line where
socket_server.sockets[0]._sock = context.wrap_socket(socket_server.sockets[0]._sock)
is written is where I have a problem, I don't know how to enable TLS on an already existing asyncio.start_server object.
The get_context() methods works well so don't worry about it btw.

HTTP error 422 in authentication responses

I have get an error for response 422. May i know how can i resolve this?
class FormsAPI:
def __init__(self, key):
self.authorization_key = personal_forms_authorization_key
def getFormInformation(self, formID):
'''
Get forms details.
return: list_form details
'''
url = 'https://api.bentley.com/forms/'
print(url)
try:
params = {'id': formID
}
headers = {'Accept': 'application/vnd.bentley.itwin-platform.v1+json',
'Authorization': self.authorization_key}
response = requests.get(url, headers=headers, params=params)
print(response)
if(response.status_code == 200):
content = jsonParser(response.text)
list_FormDetails = content
return list_FormDetails
else:
return "error"
except Exception as e:
print(e)
list_FormDetails = FormsAPI.getFormInformation(formID)
See answer from laurynasr for same question at https://github.com/imodeljs/imodeljs/discussions/1626:
422 is returned from the Forms API, not as part of the authentication -- it means that the client provided some parameters that could not be processed. The response payload contains more details.

How to post an image as a request with Flask Server API in Dart/Flutter?

I want to post a request to a Python-based API that has an image in its body. I have tried to send data with 5 methods:
await http.post()
final api = Uri.parse("https://e8f628d7.ngrok.io/detections");
Map<String, dynamic> body = {'images': image};
final response = await http.post(
api,
body: body,
);
if (response.statusCode == 200) {
final responseJson = json.decode(response.body);
print(responseJson);
}
Client().post()
Map<String, dynamic> body = {'images': image};
var client = new http.Client();
client.post("https://e8f628d7.ngrok.io/detections",body: body).then((response) {
print("Post " + response.statusCode.toString());
});
dio
MultipartRequest
final api = Uri.parse("https://e8f628d7.ngrok.io/detections");
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
var request = new http.MultipartRequest("POST", api);
var multipartFileSign = new http.MultipartFile(
'profile_pic', stream, length,
filename: path.basename(image.path));
request.files.add(multipartFileSign);
// send
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
Link of [DELETED]First Answer to this question:
if (image == null) return;
String base64Image = base64Encode(image.readAsBytesSync());
http.post(api, body: {
'images': base64Image,
}).then((res) {
print(res.statusCode);
print(json.decode(res.body));
}).catchError((err) {
print(err);
});
}
I am able to send the image and am getting a 200 success response. But, I am not sure if the image is getting altered or any problem happens while sending the image as the response is empty whereas it should have some sort of response.
This is my app.py from with which my server works:
import time
from absl import app, logging
import cv2
import numpy as np
import tensorflow as tf
from yolov3_tf2.models import (
YoloV3, YoloV3Tiny
)
from yolov3_tf2.dataset import transform_images, load_tfrecord_dataset
from yolov3_tf2.utils import draw_outputs
from flask import Flask, request, Response, jsonify, send_from_directory, abort
import os
# customize your API through the following parameters
classes_path = './data/labels/coco.names'
weights_path = './weights/yolov3.tf'
tiny = False # set to True if using a Yolov3 Tiny model
size = 416 # size images are resized to for model
output_path = './detections/' # path to output folder where images with detections are saved
num_classes = 80 # number of classes in model
# load in weights and classes
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
if tiny:
yolo = YoloV3Tiny(classes=num_classes)
else:
yolo = YoloV3(classes=num_classes)
yolo.load_weights(weights_path).expect_partial()
print('weights loaded')
class_names = [c.strip() for c in open(classes_path).readlines()]
print('classes loaded')
# Initialize Flask application
app = Flask(__name__)
# API that returns JSON with classes found in images
#app.route('/detections', methods=['POST'])
def get_detections():
raw_images = []
images = request.files.getlist("images")
image_names = []
for image in images:
image_name = image.filename
image_names.append(image_name)
image.save(os.path.join(os.getcwd(), image_name))
img_raw = tf.image.decode_image(
open(image_name, 'rb').read(), channels=3)
raw_images.append(img_raw)
num = 0
# create list for final response
response = []
for j in range(len(raw_images)):
# create list of responses for current image
responses = []
raw_img = raw_images[j]
num+=1
img = tf.expand_dims(raw_img, 0)
img = transform_images(img, size)
t1 = time.time()
boxes, scores, classes, nums = yolo(img)
t2 = time.time()
print('time: {}'.format(t2 - t1))
print('detections:')
for i in range(nums[0]):
print('\t{}, {}, {}'.format(class_names[int(classes[0][i])],
np.array(scores[0][i]),
np.array(boxes[0][i])))
responses.append({
"class": class_names[int(classes[0][i])],
"confidence": float("{0:.2f}".format(np.array(scores[0][i])*100))
})
response.append({
"image": image_names[j],
"detections": responses
})
img = cv2.cvtColor(raw_img.numpy(), cv2.COLOR_RGB2BGR)
img = draw_outputs(img, (boxes, scores, classes, nums), class_names)
cv2.imwrite(output_path + 'detection' + str(num) + '.jpg', img)
print('output saved to: {}'.format(output_path + 'detection' + str(num) + '.jpg'))
#remove temporary images
for name in image_names:
os.remove(name)
try:
return jsonify({"response":response}), 200
except FileNotFoundError:
abort(404)
# API that returns image with detections on it
#app.route('/image', methods= ['POST'])
def get_image():
image = request.files["images"]
image_name = image.filename
image.save(os.path.join(os.getcwd(), image_name))
img_raw = tf.image.decode_image(
open(image_name, 'rb').read(), channels=3)
img = tf.expand_dims(img_raw, 0)
img = transform_images(img, size)
t1 = time.time()
boxes, scores, classes, nums = yolo(img)
t2 = time.time()
print('time: {}'.format(t2 - t1))
print('detections:')
for i in range(nums[0]):
print('\t{}, {}, {}'.format(class_names[int(classes[0][i])],
np.array(scores[0][i]),
np.array(boxes[0][i])))
img = cv2.cvtColor(img_raw.numpy(), cv2.COLOR_RGB2BGR)
img = draw_outputs(img, (boxes, scores, classes, nums), class_names)
cv2.imwrite(output_path + 'detection.jpg', img)
print('output saved to: {}'.format(output_path + 'detection.jpg'))
# prepare image for response
_, img_encoded = cv2.imencode('.png', img)
response = img_encoded.tostring()
#remove temporary image
os.remove(image_name)
try:
return Response(response=response, status=200, mimetype='image/png')
except FileNotFoundError:
abort(404)
if __name__ == '__main__':
app.run(debug=True, host = '0.0.0.0', port=5000)
I try to send the same image directly through Postman and get the desired response but when I do it with the flutter app, I don't get it. Is there any possibility of the image getting altered or modified? And, is there any other method in which I can send the image to the API other than the above 3?
You need to make sure that you are using a good version of http. There was a regression recently that broke multipart form. It's safest for now to hard code the exact version in pubspec.yaml (You might want to look in pubspec.lock to see what version you were using to confirm that it was one of the ones with the error.)
http: 0.12.0+4
Then try this:
main() async {
http.MultipartRequest request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
await http.MultipartFile.fromPath(
'images',
File('kitten1.jpg').path,
contentType: MediaType('application', 'jpeg'),
),
);
http.StreamedResponse r = await request.send();
print(r.statusCode);
print(await r.stream.transform(utf8.decoder).join());
}