Giter VIP home page Giter VIP logo

telegram-node-bot's People

Contributors

antmorozov avatar babua avatar chiu0602 avatar damintsew avatar harumaro avatar iceonfire avatar infacq avatar iprxy avatar jgeewax avatar konfuze avatar maksze avatar naltox avatar paool avatar senorsen avatar zverev 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  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

telegram-node-bot's Issues

Get started

is there any boilerplate code to get started. I would like to have a good structure before starting this

`request_contact` and `request_location` for keyboards

Now it's not possible to request contact or location via runMenu and runInlineMenu methods (Link to Telegram API docs)

Maybe it can be something like that:

$.runMenu({
    message: 'This is the menu:',
    keys: {
        request_contact: true,
        text: 'Share your contact',
        callback: ($) => {
            console.log('okay')
        }
    },
    {
        request_location: true,
        text: 'Share your location',
        callback: ($) => {
            console.log('okay')
        }
    }
})

Undefined number of args?

Is there any way to route messages that may have 1 to n arguments? Putting the args into ".." or '.." seems not to work.

Не работает

Пример из доки.

'use strict';

const config = require('../config');
const Telegram = require('telegram-node-bot');
const TelegramBaseController = Telegram.TelegramBaseController;
const tg = new Telegram.Telegram(config.get('TGBOT_TOKEN'));

Telegram.Telegram is not a constructor

Ну оно и понятно

// telegram.js
module.exports = function (token) {
    return new Telegram(token)
}

a waiting state does not accept any command

When a bot is in a state of waiting, we can not perform any command. e.g. if a bot has two commands /set and /get, and actions as following:-
/set : request a user to send any number, and then answer with the number.
/get : just answer with "hello"

if we send /set and then send /get command while the bot is awaiting us to send the number, the bot will not answer on the /get command.

I think the bot has to answer on any command even if it is in the waiting state.

    tg.router.when(['set'], 'SetController')
    tg.router.when(['get'], 'GetController')
    tg.controller('SetController', ($) => {
      tg.for('set', () => {
        var form = {
          num: {
            q: 'Send any number',
            error: 'sorry, wrong input',
            validator: (input, callback) => {
              if(input['text'] && !isNaN(input['text'])) {
                callback(true)
                return
              }
              callback(false)
            }
          }
        }
        $.runForm(form, (result) => {
          $.sendMessage(result.num)
        })
      })
    })
    tg.controller('GetController', ($) => {
      tg.for('get', () => {
        $.sendMessage('hello !')
      })
    })

Private messege

How make on command in group channel bot send message user to private?

any and otherwise don't work

error TypeError: Cannot read property 'toString' of undefined
at OtherwiseController.methodForCommand (.../TelegramBaseController.js:59:34)
at controllers.forEach.e (.../MessageUpdateProcessor.js:63:44)
at Array.forEach (native)
at _getSession.then.session (.../MessageUpdateProcessor.js:54:33)
at process._tickCallback (internal/process/next_tick.js:103:7)

I added a quick fix:
(TelegramRouter.js)
commandNameForUpdate(update) {
/code here/
if( this._otherwiseController ) return 'otherwise';
else if( this._anyController ) return 'any';

}

getFile(file_id) is not working

hi,
the "getFile" method in the following controller returns "undefined". why?

tg.controller('ExampleController', ($) => { tg.for('/ex', ($) => { $.sendMessage('Send me an image!') $.waitForRequest(($) => { var photos = $.message.photo; if(photos){ photos.forEach((photo) => { console.log(tg.getFile(photo.file_id)); }) } }) }) })

Listen on any message

How do I listen on any message sent by user?
For example I want to update some internal data on location sent. Or log any user message.

runForm in groups

Hi @Naltox ,

I'm designing a bot that works in both private & group chats. The bot's privacy is set to ENABLED so it can only listen to commands and mentions. When bot asks first question in the form it cannot proceed even when I send the reply like this: @foobot answer.

When I look at the source code, I see that runForm uses waitForRequest on the back. waitForRequest uses chatId to execute the correct callback. Afaik mentions use the same chatId so it should just work but bot just doesn't work as it does in private chat. Any ideas?

Error after edit message

I tried to create a "helloworld" in this example
"tg.controller ( 'ExampleController', ($) => {
    tg.for ( '/ reg', ($) => {
         $ .sendMessage ( 'Send me your name!')
         $ .waitForRequest (($) => {
             $ .sendMessage ( 'Hi' + $ .message.text + '!')
         })
    })
}) "

after editing chat messages that I have sent for the name, your library has become to produce an error:
"Lib \ telegram.js: 532
        if (update.message [ "chat"]) {
                          ^

TypeError: Can not read property 'chat' of undefined
    at Telegram._processCommand (C: \ Users \ Den \ WebstormProjects \ telegram-bot \ node_modules \ telegram-node-bot \ lib \ telegram.js: 532: 27)
    at Array (C: \ Users \ Den \ WebstormProjects \ telegram-bot \ node_modules \ telegram-node-bot \ lib \ telegram.js: 803: 22).
    at Immediate.iter [as _onImmediate](C: Users Den WebstormProjects telegram-bot node_modules telegram-node-bot lib telegram.js: 814: 22)
    at processImmediate [as _immediateCallback](timers.js: 383: 17)
"

ReferenceError: Proxy is not defined

If I try to run the example, I get this error:

MLGBJBOEMO:circle_ci_bot jurgo.boemo$ node index.js 
/Users/jurgo.boemo/WorkspacePhun/circle_ci_bot/node_modules/telegram-node-bot/lib/localization/Ivan.js:41
        return new Proxy(this, locHandler)
                   ^

ReferenceError: Proxy is not defined
    at new Ivan (/Users/jurgo.boemo/WorkspacePhun/circle_ci_bot/node_modules/telegram-node-bot/lib/localization/Ivan.js:41:20)
    at new Telegram (/Users/jurgo.boemo/WorkspacePhun/circle_ci_bot/node_modules/telegram-node-bot/lib/Telegram.js:37:20)
    at Object.<anonymous> (/Users/jurgo.boemo/WorkspacePhun/circle_ci_bot/index.js:6:12)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:142:18)
    at node.js:939:3

my node version is 5.9.1

KeyboardButton geocode and phone number

Does the sendSticker function need to be included twice in the telegram.js file line 664?

       var funcs = [
            'sendPhoto', 'sendPhotoFromUrl', 'sendDocument', 'sendDocumentFromUrl',
            'sendMessage', 'sendLocation', 'sendAudio', 'sendAudioFromUrl', 'forwardMessage',
            'sendChatAction', '**sendSticker**', '**sendSticker**', 'sendVoice', 'sendVideo', 'waitForRequest',
            'sendContact', 'sendVenue', 'unbanChatMember', 'kickChatMember', 'runInlineMenu'
        ]

error Not Implemented

I don't know what is wrong with my code that can produce mentioned above

'use strict'

const Telegram = require('telegram-node-bot')
const TelegramBaseController = Telegram.TelegramBaseController
const tg = new Telegram.Telegram('253636404:AAFpu9GwhWZasXAQ7JvSlSIJuFSuhDH-b58')

class PembukaController extends TelegramBaseController {
    /**
     * @param {Scope} $
     */
    pembukaHandler($) {
        $.runInlineMenu({
            method: 'sendMessage', //here you must pass the method name
            params: ['Silakan pilih kitab:'],
            menu: [
                {
                    text: 'test 1', //text of the button
                    callback: (callbackQuery) => {
                        console.log(1)
                    }
                },
                {
                    text: 'Perjanjian Lama',
                    callback: (callbackQuery) => {
                        console.log(2)
                    }
                },
                {
                    text: 'Perjanjian Baharu',
                    callback: (callbackQuery) => {
                        console.log(callbackQuery)
                    }
                }
            ]
        })
    }

    get routes() {
        return {
            'start': 'pembukaHandler'
        }
    }
}

class testController extends TelegramBaseController {
    /**
     * @param {Scope} $
     */
    cariAyat($) {
        $.sendMessage('Verse ' + parseInt($.query.num2) + ': Chapter ' + parseInt($.query.num1));
    }

    get routes() {
        return {
            'qs': 'cariAyat'
        }
    }
}

class OtherwiseController extends TelegramBaseController {
    handle() {
        console.log('otherwise')
    }
}

tg.router
    .when(['start'], new PembukaController())
    .when(['/qs :num1 :num2'], new testController())
    .otherwise(new OtherwiseController())

it only happen when I run /qs 2 4

Consider to strip '/' from args in $.args

When retrieving message in controller command excluded from message but there is '/' on start.

If message is '/donwload la-la-la' we receive in controller '$.args = "/ la-la-la" '
Consider to remove starting '/' from args.

Example does’t run

Hi,

i tried to run the example from the readme.md but even that gives me an error back

const Telegram = require('telegram-node-bot')
^^^^^
SyntaxError: Use of const in strict mode.
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:945:3

… also tried running without strict mode etc.

Am i the only one getting this problems?

Best regards,
Marco

/start === /startttttt

Hi!
If I listen "/start" command tg.router.when(['/start'] and user sent any word started on "/start", for example "/starttttdds", it will be processed like a "/start"

Remove/destroy menu

Hello.
I created a menu with runMenu(). There's a way to completely destroy or remove this menu when the user clicks a specific menu button?

Thanks in advance.

Cheers.

"getMe" is not available

dears,

why "getMe" method is not available?

just this is the whole thing. :)
getMe(callback){ this.call('getMe', {}, callback) }

Wrong spelling tg.callbackQuerys

tg.callbackQuerys

Sorry for mention but spelling is wrong. Correct spelling is 'queries'.

Consider to change it to prevent errors in future and my IDE swears...

Add support inline keyboard not in inline_mode

Sorry I cant format code here :(

Add support for theese type of buttons (directly in chat) see picture.
image

I tsend this message:
$.sendMessage(funct(), { parse_mode: 'Markdown', reply_markup: JSON.stringify({ inline_keyboard: [ [{text: 'Еще факты', callback_data: 'test'}] ] }) }, (clb) => { console.log(clb) });

And then here (thanks for adding) I reveive callback_data: 'test'

`tg.callbackQuerys(($) => {

})`

But this is not very good solution. Because I want to execute editMessage and ib this siruation code may be very difficult.

Consider to change this to something like:

$.sendMessage(funct(), {
parse_mode: 'Markdown',
reply_markup: markup
}, (clb) => {
console.log(clb)
});

markup = {
inline_keyboard: [
[{text: 'Еще факты', callback: function ($) {
$.editMessage('updated text');
}]
]
}

Or

markup = {
inline_keyboard: [
{
'Еще факты' : function ($) { $.editMessage('updated text') }
}
]
}

I have some ideas how to implement this... but needs your clarifiations. Because I wrote code and you can reject it :)

How to reply to a inline button

Hi,

I can't understand how to reply to a inline button, making the spinner disappear. In the previous version, I did it with tg.answerCallbackQuery($.id)

answerInlineQuery not working?

Hi, I'm trying to do something very simple with inlineMode and not getting any results...

Here's my code:

tg.inlineMode(($) => {
  var msg = $.query
  tg.answerInlineQuery($.id, [{
    text: msg
  }])
})

I already registered inlineMode with BotFather, by the way. When I try using inlineMode the spinner works for a while and then nothing happens. Not seeing any errors in the logs either...

App crashed > 'chat' of undefined

After I updated my message, there was an error

/node_modules/telegram-node-bot/lib/telegram.js:532
if (update.message["chat"]) {

TypeError: Cannot read property 'chat' of undefined
at Telegram._processCommand (node_modules/telegram-node-bot/lib/telegram.js:532:27)
at Array. (node_modules/telegram-node-bot/lib/telegram.js:803:22)
at Immediate.iter as _onImmediate
at processImmediate as _immediateCallback

a waiting state does not accept any command

When a bot is in a state of waiting, we can not perform any command. e.g. if a bot has two commands /set and /get, and actions as following:-
/set : request a user to send any number, and then answer with the number.
/get : just answer with "hello"

if we send /set and then send /get command while the bot is awaiting us to send the number, the bot will not answer on the /get command.

I think the bot has to answer on any command even if it is in the waiting state.

    tg.router.when(['set'], 'SetController')
    tg.router.when(['get'], 'GetController')
    tg.controller('SetController', ($) => {
      tg.for('set', () => {
        var form = {
          num: {
            q: 'Send any number',
            error: 'sorry, wrong input',
            validator: (input, callback) => {
              if(input['text'] && !isNaN(input['text'])) {
                callback(true)
                return
              }
              callback(false)
            }
          }
        }
        $.runForm(form, (result) => {
          $.sendMessage(result.num)
        })
      })
    })
    tg.controller('GetController', ($) => {
      tg.for('get', () => {
        $.sendMessage('hello !')
      })
    })

send markdown message

Hi, I'm new to node.js.
how can I use .sendMessage method to send Markdown message?

clear keyboard?

I'm doing a .runMenu , and basically would like a way to clear the keyboard incase the user wants to cancel or enters something invalid.

is there a way to do this? I looked at the library and couldn't find any method of doing so.

'anyMatch' : ($) => {
   // $.clearKeyboard or something
}

Downloaded file corrupted

Hello!

Trying to download file using this code:
$.sendDocumentFromUrl(film.downloadlink, {filename: 'test.torrent', contentType: "application/octet-stream"});
Also tried with different names and different contentTypes.
But when I receive file and open in torrent I have an error that file is corrupted.

Here is the link of file whitch I want to download (http://kino-torrent.net/load/0-0-0-1446-20). Using browser downloading is complete.

Adding ability to show custom keyboards in forms

I'm considering adding a PR as well but would like to know your thoughts about it in the first place. Would you consider adding support for custom keyboards in forms?

Considering below form in which you get a boolean answer (yes/no):

...
now: {
    q: "Would you want to do this now? (y/n)",
    error: "...",
    validator: (input, callback) => {...}
},
...

I think we can add a special attribute (keyboard?) here to show a custom keyboard?

Best practice to access other controllers methods

What will be the best practice to access methods of one controller from another without creating a new instance?

For example I want to access methods of SomethingController from StartController which displays the '/start' menu.

In previous version there was a method $.routeTo('/something')

TelegramApi.js:112 body.error_code undefined

Hi, I got this error and I am using:
nodejs v6.2.2 and

"dependencies": {
"telegram-node-bot": "^3.0.4"
}

/home/pi/wpi/mica/node_modules/telegram-node-bot/lib/api/TelegramApi.js:112
if (body.error_code) {
^

TypeError: Cannot read property 'error_code' of undefined
at req.post (/home/pi/wpi/mica/node_modules/telegram-node-bot/lib/api/TelegramApi.js:112:21)
at IncomingMessage.response.on.e (/home/pi/wpi/mica/node_modules/telegram-node-bot/node_modules/tiny_request/lib/network.js:70:23)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:934:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)

Wildcard Commands

Hi There,

Thanks for the great library in the first place. Would you consider adding wildcard commands such as:

/dl_12351

Such commands exist in @music bot and is useful for bots that allows action on inline query answers.

Passing additional options to the sendMessage method is not working.

Hi,
I want to send "disable_web_page_preview" option to the sendMessage method. Not able to pass this option with sendMessage. Any option can not be add too.

When I added this option manually on the below object, it works properly.
198: var preparedOptions = this._prepareOptions(options, callback, {
199: chat_id: chatId,
200: text: text
201: })

Regards,
Okan.

sendPhoto from URL error

$.sendPhoto({ url: 'https://mysource.com/image.png', filename: 'image.png'})

Error: ENOENT: no such file or directory, open '/root/livecoinbot/node_modules/telegram-node-bot/lib/api/temp/jt2348rs0gs94urw9udi.dat'
    at Error (native)

inlineMode not working?

Hi! I'm trying to use the inlineMode mode, but it does not work. There is no response when I enter '@' in the input field. Here is my code:

`var bot = require('telegram-node-bot')(token);
bot.inlineMode(($) => {
var results = [];

for(var i = 0; i < 51; i++){
    results.push({
        type: 'gif',
        gif_url: 'http://thecatapi.com/api/images/get?format=src&size=med&type=gif&uid=' + Math.random().toString(36).substring(2),
        gif_width: 250,
        gif_height: 250,
        thumb_url: 'http://thecatapi.com/api/images/get?format=src&size=small&type=gif&uid=' + Math.random().toString(36).substring(2)
    });
}
$.paginatedAnswer(results, 10);

}); `

BotFather I sent /setinline

How to stop conversation in form?

Assume we have a form that has a special field with a validation that user don't understands how to fill it and wants to go back and see the tutorial.
How we can listen for /stop in middle of questioning form fields?

ReferenceError: Proxy is not defined

Здравствуйте, при запуске с пинг-понг вылазит ошибка:

return new Proxy(this, locHandler)
ReferenceError: Proxy is not defined
at new Ivan
Ivan.js
at new Telegram
Telegram.js

Right way of using 'otherwise'

I am getting errors when trying to set-up the otherwise controller. What is the correct way of setting up the otherwise controller, say for example to message someone with "command not found". An example would be good.

Latest Telegram message edit API breaks the bot

Edit: this is a different way to approach #25

As the title says, if a user edits a message sent to the bot, the bot breaks due to an undefined property.

Steps to reproduce:

  1. npm install telegram-node-bot
  2. Run bot w/ basic commands
  3. Send the bot a message, edit it

In telegram.js:532-539, there's

if (update.message["chat"]) {
    [...]
}

On an edited message, the correct property is update.edited_message, while on a simple message there's update.message.

I've created this patch, as I don't have the time for a pull request - https://gist.github.com/vlad-s/569da7288cfa4533637604098937a12b

Thanks.

Fail after updating message

Developing own bot, I noticed that when you update last message, application fails and never started withing given error:

if (update.message["chat"]) {
                          ^

TypeError: Cannot read property 'chat' of undefined

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.