Giter Site home page Giter Site logo

node-telegram-api's Introduction

Telegram Bots

Create and control Telegram bots easily using the new Telegram API.

npm install telegram-api

telegram-api is in beta, your feedback is appreciated, please fill an issue for any bugs you find or any suggestions you have.

If you are cloning this repository, remember to run npm install to install dependencies.

If you are looking for a real-life example of a bot written using this module, see mdibaiee/webdevrobot.

Documentation

Example

// ES6:
import Bot, { Message, File } from 'telegram-api';

// ES5:
var Bot = require('telegram-api').default;
var Message = require('telegram-api/types/Message');
var File = require('telegram-api/types/File');

var bot = new Bot({
  token: 'YOUR_TOKEN'
});

bot.start();

bot.get(/Hi|Hey|Hello|Yo/, function(message) {
  var answer = new Message().text('Hello, Sir').to(message.chat.id);

  bot.send(answer);
});

bot.command('start', function(message) {
  var welcome = new File().file('./some_photo.png').caption('Welcome').to(message.chat.id);

  bot.send(welcome);
});

// Arguments, see: https://github.com/mdibaiee/node-telegram-api/wiki/Commands
bot.command('weather <city> [date]', function(message) {
  console.log(message.args.city, message.args.date);
})

Todo

  • Webhook support (not tested, see #4)
  • Forward Type
  • BulkMessage Type
  • File Type
  • Sticker Type
  • Location Type
  • Contact Type
  • Allow remote control of bots (TCP maybe)
  • YOUR IDEAS! Fill an issue

node-telegram-api's People

Contributors

amovah avatar axfree avatar eden-lane avatar laurynas-karvelis avatar ryush00 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-telegram-api's Issues

Question invalid promise

When using Question and typing an answer instead of tapping a button, invalid promise seems not to work.

var question = new Question()
                          .text('Pick something, do not type')
                          .answers([['1'], ['2']])
                          .to(message.chat.id);
            bot.send(question).then(message => {
                console.log('Valid Answer:', message.text);
                if (message.text == '1') {
                    console.log('1 is OK');
                } else if (message.text == '2') {
                    console.log('2 is OK');
                }
            }, message => {
                console.log('Invalid:', message.text);
            });

Do I understand it correctly: if don't tap any button and type something different then Invalid should be logged to console ?

Feature: add disable_notification param

Hi.
Just tried to add silent param to your Message type and it works.

{
      key: 'notification',

      /**
       * Set disable_notification of the message
       * @param  {boolean} enable
       * @return {object} returns the message object
       */
      value: function preview() {
          var enable = arguments[0] === undefined ? true : arguments[0];

          this.properties.disable_notification = !enable;
          return this;
      }
}

Error occurs at random times: Message undefined

TypeError: Cannot read property 'chat' of undefined
    at /var/lib/openshift/581204327628e191f2000152/app-root/runtime/repo/node_modules/telegram-api/types/Base.js:86:27
    at Array.find (native)
    at Bot.listener (/var/lib/openshift/581204327628e191f2000152/app-root/runtime/repo/node_modules/telegram-api/types/Base.js:78:31)
    at emitOne (events.js:101:20)
    at Bot.emit (events.js:188:7)
    at /var/lib/openshift/581204327628e191f2000152/app-root/runtime/repo/node_modules/telegram-api/build/functions/poll.js:12:9
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Source. Could happen in any bot.command or bot.get.

KeyboardButton

I know it's a new function, but I would love to be able to use KeyboardButtons to let's say send location information to bots.

Deleting messages

Telegram Bot API - Deleting messages: https://core.telegram.org/bots/api#deleteMessage

Error: Cannot find module 'telegram-api/types/Message'

Hi. I'm getting this error when I want to run the bot.

Error: Cannot find module 'telegram-api/types/Message'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/home/mamal/Projects/Others/TLBot/main.js:1:37)
    at Module._compile (module.js:460:26)
    at normalLoader (/home/mamal/Projects/Others/TLBot/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:166:5)
    at Object.require.extensions.(anonymous function) [as .js] (/home/mamal/Projects/Others/TLBot/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:179:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/home/mamal/Projects/Others/TLBot/index.js:2:1)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

It's the line 1 of main.js

import Bot from 'telegram-api/build';

I already installed dependencies. Also the Message.js file is present in the build/types folder.

File Message Promise

Hi,

Maybe this is a bug, but when message sent with File type, the promise is not called.
I think will be useful to call promise after file upload.

Regards Andrei

Enhancement: Way to specify Arguments reply string

Would be nice if it were possible to change the Enter value for ${argname} string to something nicer regarding the command you called.

For example, for a weather command it would be nice to display something like Where do you want a forecast from?

Unexpected token 'import'

Hi,

I can't get the module working because of the (I'm guessing) use of ES6 features in your code. What I get when I run my code is an error unexpected token import in index.js:1. I have updated my version of node (now 0.12.5 running on windows 7 64 bits) and I'm using the --harmony flag.

Do you have any insights?
Thanks!

No polling, just sending messages?

Hey there,

I want to use the node-telegram-api for sending notifications from my admin panel (of a nodejs project).
I've read trough all of the docs but I couldn't find out the most efficient way to send messages without polling all time.

Should I use code like

var sendNotification = function(message){
    bot.start();
    var notification = new Message().text(message).to(adminChatID);
    bot.send(notification);
    bot.stop();
}

or is there a way to start the bot at the beginning and just stop polling updates?
Or can I simply send messages without starting?

Thanks in advance

Command arguments should accept symbols

I've built a bot, and I use a command with a optional arguments. like below

bot.command('search <name> [+count]', message => {
  console.log(message.argv);
});

Then I sent to my bot this : /search bro-yo +3 and after that I gave count argument as undefined.

I think the problem is your regexp. because when I sent to my bot /search bro +3, everything was OK.

How can i forward Message?

Hi, how do I forward a text to a specific user?

bot.get(/Hi|hi|yuo|oh/, function(message) {  
  var gets = new Forward().from(@User);
  bot.send(gets);
});

Close connection

Would be handy to have a method to close the connection at any given time.

Bug: Cannot return invalid text for questions

The input is:

bot.command('mcserver [ip]', function(message) {
    if (message.args.ip !== undefined) {
/* Ignore this part, it works correctly */
    }
    else {
        const q = new Question()
                      .text('Type in the address, or click the Cancel button.')
                      .answers([['Cancel']])
                      .to(message.chat.id);
        bot.send(q).then(message => {
          console.log('Valid Answer:', message.text);
        }, msg => {
          console.log('Invalid:', msg.text);
        });
    }
});

The output is:

{ message_id: 163,
  from: 
   { id: 265228448,
     first_name: 'Austin',
     last_name: 'Huang',
     username: 'austinhuang' },
  chat: 
   { id: 265228448,
     first_name: 'Austin',
     last_name: 'Huang',
     username: 'austinhuang',
     type: 'private' },
  date: 1477604906,
  text: 'test' }
(node:27815) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'text' of undefined
(node:27815) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

#20

SyntaxError: Unexpected token )

Hi, when i run demo.js I got this error:

smartBot.start().then(() => {
                       ^
SyntaxError: Unexpected token )
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

What's going wrong?

Thanks for build this package!

Send file with file_id

How can i send an image by set file_id?
I tried:

bot.send(new File().file('FILEIDXXXXX','image').to(chat));

But the response is:

Error: value required in setHeader("Content-Length", value).
at ClientRequest.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at FormData. (/home/fenix/chatBot/node_modules/form-data/lib/form_data.js:321:13)
at /home/fenix/chatBot/node_modules/form-data/lib/form_data.js:265:7
at /home/fenix/chatBot/node_modules/async/lib/async.js:251:17
at done (/home/fenix/chatBot/node_modules/async/lib/async.js:126:15)
at /home/fenix/chatBot/node_modules/async/lib/async.js:32:16
at /home/fenix/chatBot/node_modules/async/lib/async.js:248:21
at /home/fenix/chatBot/node_modules/async/lib/async.js:572:34
at /home/fenix/chatBot/node_modules/form-data/lib/form_data.js:105:13
at FSReqWrap.oncomplete (fs.js:82:15)

So i think that is not correct and i can't find an example, what can i do?
Thanks!

Keyboards

how to set a custom keyboard with this package?
we must define keyboard on every message that i recieve?

Way to use Webhooks

Currently this API uses polling for updates (i guess).
It would be nice if you could configure it to not poll for updates and offer a method to input messages received by webhooks.

This way the user could fire up a express/koa/hapi server and feed the payload from webhookts to the bot.

Would that be clever?

ERR_UNHANDLED_ERROR error

Error [ERR_UNHANDLED_ERROR]: Unhandled error. ([object Object])
at Bot.emit (events.js:171:17)
at Bot.EventEmitter.emit (domain.js:442:20)
at /root/nodeapp/node_modules/telegram-api/build/functions/poll.js:19:9
at run (/root/nodeapp/node_modules/core-js/modules/es6.promise.js:75:22)
at /root/nodeapp/node_modules/core-js/modules/es6.promise.js:92:30
at flush (/root/nodeapp/node_modules/core-js/modules/_microtask.js:18:9)
at process._tickCallback (internal/process/next_tick.js:61:11)

What I have:
telegram-api : v4.1.0
OS : Ubuntu 16.04.3 x64
Node js : v10.2.1
npm : v6.4.1

The code I use:

var bot = new Bot({
  token: config.botkey
});

bot.on('command-notfound', message => {
  if (message.chat.id > 0) {
    bot.send(new Message().text('Command not found').to(message.chat.id));
  }
});

async function notifyUser(chatId, msg, options) {
  try{
    await bot.send(new Message().text(msg).to(chatId));
    logger.info('test was sent');
  } catch(ex){
    logger.error('error wile sending : ' + JSON.stringify(ex))
  }
}

bot.start();

NPM Registry broke. Redo your publish.

Error:

Error: Cannot find module 'telegram-api'

I have uninstalled it and reinstalled, but still same error. In fact, the index.js and source files are GONE.
screen shot 2016-11-22 at 4 06 34 pm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.