在Python Telethon库和Node.js之间交换数据



我面临这样一个问题:在我的小测试应用程序中,我有简单的node.js (express)服务器和python脚本,它允许我使用Telethon库与Telegram API进行交互。在我的场景中,我必须提供我的python脚本一个电话号码和密码。这些数据是在输入模式下询问的,所以我不知道,我如何能够:

  1. 接受node.js端python脚本的输入请求;
  2. 通过node.js提供这些凭据,并通过python的输入传递它们;
  3. 重复这个动作几次以获得我需要的所有信息。

这些是我的测试文件:

file.py

import os
from telethon import TelegramClient
api_id = 12345
api_hash = 'hash'
session = 'testing'
proxy = None
client = TelegramClient(session, api_id, api_hash, proxy=proxy).start()

def get_ids_list():
ids_dict = {}
async def do_fetch():
async for dialog in client.iter_dialogs():
ids_dict[dialog.name] = dialog.id
with client:
client.loop.run_until_complete(do_fetch())
return ids_dict

def print_ids_list():
async def do_print():
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id)
with client:
client.loop.run_until_complete(do_print())

print_ids_list()

当这个脚本运行时,我被提示以下输入:

Please enter your phone (or bot token):

这是我的index.js,我想把准备好的数据传递给这个输入:

import express from "express";
import { spawn } from "child_process";
const app = express();
const port = 3000;
app.get("/", (req, res) => {
var myPythonScript = "path/to/file.py";
var pythonExecutable = "python";
var uint8arrayToString = function (data) {
return String.fromCharCode.apply(null, data);
};
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);
scriptExecution.stdout.on("data", (data) => {
console.log(uint8arrayToString(data));
});
scriptExecution.stderr.on("data", (data) => {
console.log(uint8arrayToString(data));
});
scriptExecution.on("exit", (code) => {
console.log("Process quit with code : " + code);
});
});
app.listen(port, () =>
console.log(`Example app listening on port ${port}!`)
);

那么,有办法解决这种情况吗?

使用with client相当于client.start(),如前所述:

默认情况下,此方法将是交互式的(如果需要则询问用户输入),并且如果启用也将处理2FA。

你需要做它手动做的事情,删除with块,并创建一个函数来验证(或确认如果已经授权)。

表示最小函数示例:

....
if not client.is_connected():
await client.connect()
if not await client.is_user_authorized():
await client.send_code_request(phone)
# get the code somehow, and in a reasonably fast way
try:
await client.sign_in(phone, code)
except telethon.errors.SessionPasswordNeededError:
'''
Retry with password.
note: it's necessary to make it error once 
even if you know you have a pass, iow don't pass password the first time.
'''
await client.sign_in(phone, code, password=password)
return client
else:
return client

在等待所需参数成功登录的同时,顺序地和交互地处理步骤,同时还要记住,在代码过期之前有时间限制,这是你的任务,根据你的用例处理任何未定义的行为。

最新更新