首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >创建一个将侦听电报频道的应用程序

创建一个将侦听电报频道的应用程序
EN

Stack Overflow用户
提问于 2017-12-14 01:03:48
回答 4查看 7.9K关注 0票数 16

首先,请注意,,这与创建bot无关。

我的目标是创建一个应用程序,该应用程序将简单地侦听我将提供给它的帐户订阅的任意数量的电报通道,并检索发送到这些频道的所有消息(就像我是一个普通用户)。我猜我需要

  • 用我帐户的电话号码来验证我自己
  • 能够为所有传入消息设置每个通道的回调侦听器或通用侦听器。

我已经在telegram api上看了几天了,我对它的工作方式感到非常困惑。在放弃了它之后,我开始研究现成的实现,主要是针对NodeJS的,但仍然无法找到具体的解决方案。我正在用电报-js api测试一些东西,但是直接使用node运行它是行不通的。它需要在浏览器中运行吗?这方面是否有更精简的方法?最好是有好文件的东西。

PS:我精通Java和Javascript,所以我已经根据这些语言对库进行了排序。

编辑:

下面是我编写的代码(实质上是复制了一个示例)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
var { Telegram } = require("../libs/telegram");
var TypeLanguage = require("telegram-tl-node") ;
var MTProto = require("telegram-mt-node");

var schema = require("../libs/api-schema.json");

const APP_ID = "111111";
const APP_HASH = "fb6da8f6abdf876abd6a9d7bf6";
const SERVER = { host: "111.111.111.11", port: "443" };
const config = {
  id: APP_ID,
  hash: APP_HASH,
  version: '0.0.1',
  lang_code: 'en',
  authKey: null
};

let telegram = new Telegram(MTProto, TypeLanguage);
telegram.useSchema(schema);
addPublicKeys(telegram);

let connection = new MTProto.net.HttpConnection(SERVER);

let client = telegram.createClient();
client.setConnection(connection);

connection.connect(function() {
  let ready = client.setup(config);
  ready.then(function(client) {
    // it never resolves this promise
    function callback(response) {
      console.log(response);
    }
    client.callApi("help.getConfig").then(callback, callback);
  });
});

它使用了这两个lib:电报-mt节点 电报-tl节点

EN

回答 4

Stack Overflow用户

发布于 2020-06-13 09:36:23

迟答,但可能对他人有帮助。

您可以利用mtproto核使用常规电报帐户进行身份验证,并收听更新(或者对电报客户做任何您能做的事情,真的)

下面是我编写的一个示例脚本,它侦听来自用户订阅的通道/超级组的新消息:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
const { MTProto, getSRPParams } = require('@mtproto/core');
const prompts = require('prompts');

const api_id = ...; // insert api_id here
const api_hash = ' ... '; // insert api_hash here

async function getPhone() {
    return (await prompts({
        type: 'text',
        name: 'phone',
        message: 'Enter your phone number:'
    })).phone
}

async function getCode() {
    // you can implement your code fetching strategy here
    return (await prompts({
        type: 'text',
        name: 'code',
        message: 'Enter the code sent:',
    })).code
}

async function getPassword() {
    return (await prompts({
        type: 'text',
        name: 'password',
        message: 'Enter Password:',
    })).password
}


const mtproto = new MTProto({
    api_id,
    api_hash,
});

function startListener() {
    console.log('[+] starting listener')
    mtproto.updates.on('updates', ({ updates }) => {
        const newChannelMessages = updates.filter((update) => update._ === 'updateNewChannelMessage').map(({ message }) => message) // filter `updateNewChannelMessage` types only and extract the 'message' object

        for (const message of newChannelMessages) {
            // printing new channel messages
            console.log(`[${message.to_id.channel_id}] ${message.message}`)
        }
    });
}


// checking authentication status
mtproto
    .call('users.getFullUser', {
        id: {
            _: 'inputUserSelf',
        },
    })
    .then(startListener) // means the user is logged in -> so start the listener
    .catch(async error => {

        // The user is not logged in
        console.log('[+] You must log in')
        const phone_number = await getPhone()

        mtproto.call('auth.sendCode', {
            phone_number: phone_number,
            settings: {
                _: 'codeSettings',
            },
        })
            .catch(error => {
                if (error.error_message.includes('_MIGRATE_')) {
                    const [type, nextDcId] = error.error_message.split('_MIGRATE_');

                    mtproto.setDefaultDc(+nextDcId);

                    return sendCode(phone_number);
                }
            })
            .then(async result => {
                return mtproto.call('auth.signIn', {
                    phone_code: await getCode(),
                    phone_number: phone_number,
                    phone_code_hash: result.phone_code_hash,
                });
            })
            .catch(error => {
                if (error.error_message === 'SESSION_PASSWORD_NEEDED') {
                    return mtproto.call('account.getPassword').then(async result => {
                        const { srp_id, current_algo, srp_B } = result;
                        const { salt1, salt2, g, p } = current_algo;

                        const { A, M1 } = await getSRPParams({
                            g,
                            p,
                            salt1,
                            salt2,
                            gB: srp_B,
                            password: await getPassword(),
                        });

                        return mtproto.call('auth.checkPassword', {
                            password: {
                                _: 'inputCheckPasswordSRP',
                                srp_id,
                                A,
                                M1,
                            },
                        });
                    });
                }
            })
            .then(result => {
                console.log('[+] successfully authenticated');
                // start listener since the user has logged in now
                startListener()
            });
    })

您可以从api_idapi_hash中找到https://my.telegram.org的值。

在第一次运行时,脚本提示用户输入phone_number、代码和密码。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[+] You must log in
√ Enter your phone number: ... <phone_number>
√ Enter the code sent: ... <code>
√ Enter Password: ... <2FA password>

在身份验证结束后,运行一个示例输出:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[+] starting listener
[13820XXXXX] Ja
[13820XXXXX] Bis bald guys��
[13820XXXXX] Ja.[13820XXXXX] Bis später
[13820XXXXX] Jaaa�

我检查身份验证状态的方式是从这里开始

值得检查的可选库:空气图 (tdlib)和格莱士,这些库激活了编写时的时间(可以用来创建相同的行为)

票数 12
EN

Stack Overflow用户

发布于 2022-01-31 16:26:26

我使用了gram.js库,实际上做了

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { TelegramClient } from 'telegram'
TelegramClient().addEventHandler(handler, { chats: [1234567890] })

机器人不需要成为您想要收听的频道的成员。

我的代码作为Node.js应用程序运行。

您需要首先通过电报与https://t.me/BotFather交谈来创建令牌。

票数 4
EN

Stack Overflow用户

发布于 2022-10-01 11:34:11

这里是我使用语法的工作代码,它完全在nodejs上。没有任何延迟地从所有频道接收所有的消息。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import {
  TelegramClient
} from "telegram";
import {
  NewMessage,
  NewMessageEvent
} from "telegram/events";
import {
  StringSession
} from "telegram/sessions";
const input = require("input");

const apiId = 1233456677;
const apiHash = "xxxxxxxxxxxxxxxxx";
let stringSession = new StringSession("xxxxxxxxxxxxxxxxx");

(async() => {
  console.log("Loading interactive example...");
  const client = new TelegramClient(stringSession, apiId, apiHash, {
    connectionRetries: 5,
  });
  await client.start({
    phoneNumber: async() => await input.text("Please enter your number: "),
    password: async() => await input.text("Please enter your password: "),
    phoneCode: async() =>
      await input.text("Please enter the code you received: "),
    onError: (err) => console.log(err),
  });
  console.log("You should now be connected.");
  const session: any = client.session.save();
  stringSession = new StringSession(session); // Save this string to avoid logging in again - specially in nodemon
  console.log(client.session.save()); // --> you can also copy this session from your console once you get it and paste it in line number 8 - new StringSession("XXXXXXXXXXXXXX")
  // once you saved add the JWT Token on line no. 8 as mention above next time you will getting directly connected.
  await client.sendMessage("me", {
    message: "Hello!"
  });
  async function handler(event: NewMessageEvent) {
    console.log("[newmessage]", event);
  }
  client.addEventHandler(handler, new NewMessage({}));
})();

备注-忽略了“运行代码片段”,因为这是添加完整代码而不是格式化的最佳方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47809485

复制
相关文章
spark (java API) 在Intellij IDEA中开发并运行
王小雷
2018/01/02
3.8K0
spark (java API) 在Intellij IDEA中开发并运行
quartus ii运行错误_安装quartus时弹出错误
Info: ******************************************************************* Info: Running Quartus II 64-Bit Analysis & Synthesis Info: Version 11.0 Build 157 04/27/2011 SJ Full Version Info: Processing started: Thu May 15 13:09:59 2014 Info: Command: quartus_map –read_settings_files=on –write_settings_files=off simulate -c simulate Info: Parallel compilation is enabled and will use 2 of the 2 processors detected Info: Found 1 design units, including 1 entities, in source file simulate.v Info: Found entity 1: modelsim_test Error: Top-level design entity “simulate” is undefined
全栈程序员站长
2022/11/04
5.1K0
quartus ii运行错误_安装quartus时弹出错误
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( No module named ‘threadpool‘ )
安装完 Python 插件后 , 在 import threadpool 代码下 , 报如下错误 ;
韩曙亮
2023/03/29
7510
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( No module named ‘threadpool‘ )
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( End of statement expected )
将 Python SDK 从 Python 2.7 升级为 Python3.10 后 , 报如下报错 ;
韩曙亮
2023/03/29
5430
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( End of statement expected )
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( No module named ‘numpy‘ )
这个错误大概是 numpy-1.21.2 与 Python3.10 版本不匹配导致 ;
韩曙亮
2023/03/29
9620
【错误记录】Mac 中 IntelliJ IDEA 运行 Python 程序报错 ( No module named ‘numpy‘ )
解决在 Spring Boot 中运行 JUnit 测试遇到的 NoSuchMethodError 错误
在本文章中,我们将会解决在 Spring Boot 运行测试的时候,得到 NoSuchMethodError 和 NoClassDefFoundError 的 JUnit 错误。
HoneyMoose
2022/08/25
2.8K0
解决在 Spring Boot 中运行 JUnit 测试遇到的 NoSuchMethodError 错误
DW 在onload运行recordset find.html时 发生了以下javascript错误
这两天打开Dreamweaver CS5,总是弹出一个错误,写着:   在onLoad运行RecordsetFind.htm时,发生了以下JavaScript错误:   在文件“RecordsetFind”中:   findRsisnotdefined   在关闭Dreamweaver的时候也会弹出一个类似的错误, 原因:DW 的配置信息出错了,可能是上次使用非法关闭造成的。   在网上查了一下,找到了解决方法。   方法如下: 删除该目录中对应的Dreamweaver版本文件夹。 xp系统,目录 C:/
deepcc
2018/05/16
1.6K0
关于首次运行Hadoop的Grep案例时出现的错误
重点关注这句“19/05/14 18:26:55 INFO metrics.MetricsUtil: Unable to obtain hostName java.net.UnknownHostException: hadoop101: hadoop101: Temporary failure in name resolution”,其为hostname可能存在问题,因此去查看/etc/sysconfig/network文件和/etc/hosts文件,发现其network文件中的“HOSTNAME=”后多打了一个空格,把其去掉,即可,问题解决
可定
2020/04/20
4.4K0
【错误记录】IntelliJ IDEA 中编译运行报错 ( 当前设置 GBK 编码 | 错误: 编码UTF-8的不可映射字�? )
文章目录 一、 报错信息 二、 解决方案 一、 报错信息 ---- 当前的 IntelliJ IDEA 设置的编码为 GBK 编码 , 选择 " 菜单栏 / File / Settings " 选项 , 在 " File Encodings " 中 , 查看 工程的编码 , 运行时报错 : 在中文注释的位置 , 编码报错 ; D:\002_Project\003_Java_Work\Exsample\src\main\java\ArrowCanvas.java:17: 错误: 编码UTF-8的不可映
韩曙亮
2023/04/01
5.2K0
【错误记录】IntelliJ IDEA 中编译运行报错 ( 当前设置 GBK 编码 | 错误: 编码UTF-8的不可映射字�? )
在IntelliJ IDEA中配置maven
在IntelliJ IDEA中配置maven 打开-File-Settings  5.新建maven WEB项目 打开-File-New-Project  点击NEXT  点
似水的流年
2018/01/18
1.3K0
在IntelliJ IDEA中配置maven
在IntelliJ IDEA中配置maven
在IntelliJ IDEA中配置maven 打开-File-Settings 
似水的流年
2019/12/08
9650
在IntelliJ IDEA中配置maven
在IntelliJ IDEA中配置maven 打开-File-Settings 
似水的流年
2018/01/14
1.1K0
在eclipse中运行hive时显示Software caused connection ab...
启动hive机器thrift监听程序: hadoop@ubuntu118:~$ hive --service hiveserver 50031 Starting Hive Thrift Server This usage has been deprecated, consider using the new command line syntax (run with -h to see usage information) WARNING: org.apache.hadoop.metrics.jvm.Eve
闵开慧
2018/03/30
1.2K0
在eclipse中运行hbase时显示Could not resolve the DNS na...
ERROR hbase.HServerAddress: Could not resolve the DNS name of ubuntu118 Exception in thread "main" java.lang.IllegalArgumentException: hostname can't be null at java.net.InetSocketAddress.<init>(InetSocketAddress.java:121) at org.apache.had
闵开慧
2018/03/30
1.2K0
R语言在RCT中调整基线时对错误指定的稳健性
众所周知,调整一个或多个基线协变量可以增加随机对照试验中的统计功效。调整分析未被更广泛使用的一个原因可能是因为研究人员可能担心如果基线协变量的影响在结果的回归模型中没有正确建模,结果可能会有偏差。
拓端
2020/07/16
1.7K0
IntelliJ IDEA 运行项目的时候提示 Command line is too long 错误
这时候你需要调整运行项目的配置,将 Configuration 中的 Shorten Command Line 修改为 JAR 就可以了。
HoneyMoose
2019/10/12
1.7K0
IntelliJ IDEA 运行项目的时候提示 Command line is too long 错误
IntelliJ IDEA 运行项目的时候提示 Command line is too long 错误
这时候你需要调整运行项目的配置,将 Configuration 中的 Shorten Command Line 修改为 JAR 就可以了。
HoneyMoose
2019/10/10
6100
单元测试的IntelliJ IDEA的常用插件
这就是TestMain最好放在和工程Application类所在包相同路径下的原因。
MickyInvQ
2021/03/04
2.1K0
单元测试的IntelliJ IDEA的常用插件
在Intellij IDEA中如何使用Debug!
Debug用来追踪代码的运行流程,通常在程序运行过程中出现异常,启用Debug模式可以分析定位异常发生的位置,以及在运行过程中参数的变化。通常我们也可以启用Debug模式来跟踪代码的运行流程去学习三方框架的源码。
Java3y
2019/05/21
4.7K0
在Intellij IDEA中如何使用Debug!
idea运行缓慢_intellij idea运行不了
  1、由于默认的jvm太多,但是实际上可以用的比较少,我们可以这样进行设置,使用鼠标右键单击桌面上的IntelliJ IDEA软件图标,选择“打开文件所在的位置”一栏
全栈程序员站长
2022/10/02
9170
idea运行缓慢_intellij idea运行不了

相似问题

在Intellij 13中运行单元测试

26

在intellij中运行单元测试用例时出现空测试套件错误

110

java.lang.StackOverflowError on IntelliJ

32

在IntelliJ中运行单元测试,并在类中出现错误

40

在Maven的帮助下在FileNotFoundException中运行IntelliJ时获取IntelliJ错误

20
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文