简体   繁体   English

在 Python Telethon 图书馆和 Node.js 之间交换数据

[英]Exchanging data between Python Telethon library and Node.js

I faced such a problem: in my small test app I have simple node.js (express) server and python script, which allows me to interact with Telegram API using Telethon library.我遇到了这样一个问题:在我的小型测试应用程序中,我有简单的 node.js(快速)服务器和 python 脚本,它允许我使用 Telethon 库与 Telegram API 进行交互。 In my scenario I have to provide my python script a phone number and a password.在我的场景中,我必须为我的 python 脚本提供电话号码和密码。 These data is asked in the input mode, so I can't figure out, how am I able to:这些数据是在输入模式下询问的,所以我想不通,我怎么能:

  1. Accept input request from python script on node.js side;在node.js端接受来自python脚本的输入请求;
  2. Provide these credentials by node.js and pass them back via python's input;通过 node.js 提供这些凭据,并通过 python 的输入将它们传回;
  3. Repeat this actions several times to gain all info I need.多次重复此操作以获得我需要的所有信息。

These are my test files:这些是我的测试文件:

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()

When this script is run, I'm prompted the following input:运行此脚本时,系统会提示我输入以下内容:

Please enter your phone (or bot token):

And this is my index.js , in which I want to pass prepared data to this input:这是我的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}!`)
);

So, is there a way to solve this case?那么,有没有办法解决这个问题呢?

Using with client is equivalent to client.start() , and as stated: with client使用等同于client.start() ,并且如前所述:

By default, this method will be interactive (asking for user input if needed), and will handle 2FA if enabled too.默认情况下,此方法将是交互式的(如果需要,会询问用户输入),并且如果启用也会处理 2FA。

You need to instead do what it does manually, remove with block, and make a function to authenticate (or confirm if already authorized).您需要改为手动执行它的操作,删除with ,并制作 function 进行身份验证(或确认是否已授权)。

for a minimal func example:对于最小的功能示例:

    ....
    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

Dealing with the steps sequentially and interactivly while waiting for needed params to login successfully while also keeping in mind you have time limit until code expires is your task to handle any of their undefined behavior dependant on your usecase.在等待所需的参数成功登录的同时按顺序和交互地处理这些步骤,同时还要记住你有时间限制直到代码过期是你的任务是根据你的用例处理它们的任何未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM