Code Monkey home page Code Monkey logo

telebot's Issues

Не работает webhook

Добрый день!

Не работает webhook.js из примера (ngrok работает).

Вставил token,ip и поменял название для сгенерированных ключей. Ключи с другими библиотеками работают (проверял для Telegram под Nodejs и Python).

const bot = new TeleBot({
token: '12345678:FGGRGRGfcdefefUIOPbbb',
webhook: {
// Self-signed certificate:
key: './webhook_pkey.pem',
cert: './webhook_cert.pem',
url: 'https://95.12.34.56',
host: '0.0.0.0',
port: 443
}
});

В консоли показывается установка webhook и старт безопасного сервера, а дальше тишина. На присланные команды не отвечает.

[bot.webhook] set to "https://95.12.34.56/12345678:FGGRGRGfcdefefUIOPbbb"
[bot.webhook] started secure server on "0.0.0.0:443"

[ask] telegram message gateway

is it possible to make telebot become message gateway?
so the id is my phone number but act like bot...
if someone message me(my phone number), my account will auto reply like bot...
is it possible?
pardon me if i ask here... :D

keyboardbutton on chat when pressed

is it possible when i click button then what i press is show on chat field,
for example
if there is a button keyboard [1] [2] [3]
when i click on [1], 1 is shown on chat field not on chat screen as default
and when i click [3][2][1], chat field become 321 and when i press enter 321 is shown
on the screen...
and is it possible?
@kosmodrey @G07cha @Pyriaxis

Unexpected Character {

When I launch my script that requires Telebot I keep getting:

/node_modules/telebot/lib/telebot.js:86
      let { url, cert } = this.webhook;
          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/renevlugt/Development/albys_bot/index.js:4:17)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

' instead of ` for Europe

Hello, in Europe we don't have on keyboard the ` key, we just have ' or " ...is there a way to let strings like

Hello, ${ firstName } ${ lastName }!

work?

I tried with
'Hello, '+${ firstName }!
and
'Hello, ${ firstName }!'

but it doesn't work!

Parse_mode

Hi! How I can set parse_mod to 'HTML' in sendMessage function or other?

Context

Hi there,

let's say I have the following code:

bot.on('/start', msg => {
  let markup = bot.inlineKeyboard([
    [
      bot.inlineButton('Search by name', { callback: '/search_name' }),
      bot.inlineButton('Search by fullname, { callback: '/search_fullname' }),
    ]
  ]);

  return bot.sendMessage(msg.from.id, `Please choose one option`, { markup });
});

bot.on('callbackQuery', function(msg) {

  // Send confirm
  bot.answerCallback(msg.id);

  let response;
  if(msg.data === '/search_name') {
    response = `Please enter a name`;
  } else if(msg.data === '/search_fullname') {
    response = `Please enter a full name`;
  }

  return bot.sendMessage(msg.from.id, response);
});

bot.on('text', msg => {

   // How can I know here is it a name or full name search?
});

I need to know the user's context, what did he choose on previous step

Is it possible with this library?

Send Message without Event

Hi mullwar

Many thanks for your awesome API!

I'm trying to use your API to send simple notifications without an event and I'm using following code:
bot.sendMessage(<user-id>, "message");

But I get following error:
(node:5735) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object]

I've created the bot object as following:
const TeleBot = require('telebot'); const bot = new TeleBot({ token: '<token>, // Required. Telegram Bot API token. webhook: { // Optional. Use webhook instead of polling. key: './cert/key.pem', // Optional. Private key for server. cert: './cert/cert.pem', // Optional. Public key. url: 'https://127.0.0.1', // HTTPS url to send updates to. host: '127.0.0.1', // Webhook server host. port: 88 // Server port. } });

I'm listening via an express server.

Could you help me out?

Thank you very much!!

Cannot send image as buffer

When I'm sending the image as buffer server returns 400 code with an error like: "Incorrect format, image must be .png .jpg .tiff...", I've tried to fix it by myself by adding "mime type" and filename with extension but it's didn't worked for me.

Minimum amount of code to reproduce(requies valid image named "node-small.jpg" in "data" folder):

const fs = require('fs');

let buffer = fs.readFileSync(`${__dirname}/data/node-small.jpg`);
bot.sendPhoto(USER, buffer).catch(err => console.log(err));

Node 0.10.33

I did also another change to the code, which adds support for older node.
Do you need it? It uglifies the code a bit and adds dependency to Promise library

Send own contact via inline buttons and button labels without '/'

Two simple questions:

  1. is it possible to send my own contact via an inline buttons? Something like
        let markup = bot.inlineKeyboard([
          [
            // Button in first row with command callback
            bot.inlineButton('Send Contact', { callback: 'contact' }),
          ],
          [
            // Second row with regular command button
            bot.inlineButton('back', { callback: '/back' })
          ]
        ]);
  1. is it possible to have button labels without the '/' bar? Like
let markup = bot.keyboard(
          [
            [bot.button("contact", "send contact")],
            ["back"]
          ]
          , { resize: true }
        );

bot.on( ["/back"]  , msg => {
    let markup = ....;
  return bot.sendMessage(msg.from.id, "Menu", {markup});
});

Thanks!

Local testing

I write the bot on my computer.
How i can the bot testing local on my computer?

image

here my settings.

acess list

Hello Kosmodrey,

How could I create a way to only users listed by name @example in a TXT file would have access to start the bot ? And if the user does not have the list , appear a message Access denied .

I have an example?

UnhandledPromiseRejectionWarning: Unhandled promise rejection

Hi!

I use that method bot.on('callbackQuery', (msg) => {...}) to update inlineButtons, but if set same buttons like last time - I catch nodejs error:
(node:11721) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object] (node:11721) 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.

Could you help to resolve this issue?

Is it possible to have http proxy support ?

Hello,

First of all, I really appreciate your work.
Is it possible to add proxy support ?

exemple :

const bot: TeleBot = new TeleBot( {
    token: botToken,
    http_proxy: {
        host: "[MyProxy]",
        port: 8080,
        username: "[MyUsername]",
        password: "[MyPwd]"
    },
    polling: {
        ...
    }
});

Thank you !

Download a document

I want to download a document. I'm using bot.getFile method but the result object does not have "file_path". how can i do this? (I'm new to node)

channel created and info about channel

hi.tnx in advance for ur amazing telebot.
in message event we have 'channelCreated' event.i think that it doesn't work properly.what is that and how to use it.
suppose my bot added to channel how can i access to their info like admin user, membercount, title,...
how can i authorize admin user of channel send pv to me.

How to distinguish location event from a reply to an ask for location?

I my code I need to ask a location for a specific purpose, so I use the ask plugin with something like :

...
bot.sendMessage(id, 'Please attach your location here!', {ask: 'location'});
...
bot.on('ask.location', msg => { ... } );
...

It works perfectly, however I also have another piece of code that trigger on every 'location' event at the same time of the 'ask.location' event :

bot.on('location', msg => { ... } );

Is there a way to avoid the last when the location is in reply of a question ('ask.location')? What is your advice?

Override 'text' event

i got two events, one for /hello command, and one for text message type. But every time i use the /hello command, the response from text events also called. How can i avoid this?

Sending silent messages is not working

I'm trying to send a message without it sending a notification, I use the code below. It doesn't matter if I set notification to true or false, a notification will always be send. Am I using the wrong name for the object key or is it in fact failing?

bot.sendMessage(config.telegramGroupID, "Some message", {parseMode: "markdown", replyToMessage: null, replyMarkup: null, notification: false, webPreview: true});

bug? title ignored in Audio Messages

This is the example where I am trying to "change"/write the title of the audio file:

bot.on(['/material'], (msg) => {
var maxNumberElements = 20;
var index = randomIntInc(0,maxNumberElements);
var groupID = '113,129';
var endpoint = 'http://mydomain.com/api/podcast/bygroup?active=true&group=' +
groupID + '&limit=' + maxNumberElements + '&radio=' + radioID + '&sort=startDate%20DESC';
var urlPodcast = '';
var titlePodcast = '';

request
    .get(endpoint)
    .set('Accept', 'application/json')
    .set('Authorization', 'Bearer ' + token4API)
    .end(function(error, response) {
        if (error) {
            console.log('MaratonRadioBot error: ' + error);
        }
        urlPodcast = webAddrRoot4mp3 + response.body[index].mp3Url;
        titlePodcast = response.body[index].title;
        console.log('Titulo del ultimo podcast: ' + titlePodcast);
        console.log('URL del ultimo podcast: ' + urlPodcast);
        bot.sendMessage(msg.from.id, "Descargando el podcast: " + titlePodcast + "...");
        return bot.sendAudio(msg.from.id, urlPodcast, {title: titlePodcast});
});

});

In the console I can see the title and the url of the mp3, but when this code is executed, the title is always took from the metadata of the mp3, not from my variable "titlePodcast".
Could you give me some insight?
Thanks in advaced!

how to get contact number with bot.on event 'contact' ?

how can i get user phone number with bot on event contact ?
is it a way to get it ?

bot.on('contact', (msg,info)=>{
const id = msg.from.id;
let day = msg.text;
console.log(info);
return bot.sendMessage(
id, 'thanks for contact number'
);
});

Message Identified Not specified

I have this event:

bot.on('/help', msg => {
    
    return bot.sendMessage(msg.from.id, 'Getting time...').then(re => {
        var chatId = msg.from.id;
        var msgId = re.result.message_id;
        bot.editText(
            { chatId , msgId }, `edited`,
            { parse: 'html' }
        ).catch(error => console.log('Error:', error));   
    });
});

i want to edit the response of my bot, but I always receive this message error:
Bad Request: Message Identified Not specified

But when I print in console the message_id of the response it exists!.

Is Something wrong with the code?

Метод getFile возвращает неправильный url

Мой код

bot.on('photo', msg => {
  console.log(msg);
  let id = msg.from.id;
  let file_id = msg.photo[0].file_id;
  console.log('file_id', file_id);
  
  return bot.getFile(file_id).then(x => {
    console.log("GetFileResp", x);
    bot.sendMessage(id, 'File Link: ${ x.fileLink }');
  });
});

Вывод

{ message_id: 48,
  from: { id: ******, first_name: 'Pavel', last_name: '*' },
  chat: 
   { id: ******,
     first_name: 'Pavel',
     last_name: '*',
     type: 'private' },
  date: 1491734458,
  photo: 
   [ { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC',
       file_size: 310,
       width: 90,
       height: 48 },
     { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABCOUaDKWXy_jG_0BAAEC',
       file_size: 326,
       width: 106,
       height: 56 } ] }
file_id AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC
GetFileResp { file_id: 'AgADAgADyqcxGxMUUUu8UWjZauY_gQFNtw0ABKdvTbkKjg0KHP0BAAEC',
  file_size: 310,
  file_path: 'photos/file_1.jpg',
  fileLink: 'undefinedphotos/file_1.jpg' }

Keyboard & Button

Здравствуй,
не мог бы ты привести пример кода для формирования клавиатуры и кнопок, использующий твои кастомные методы?

cannot find module

hmm, when i add new module like this on script
bot.use(require('modules/ask.js')) and running it;

it say error : cannot find module 'modules/ask.js' anyone ever got this error?

How can I get Location data back from a keyboard?

I have a bot that does a series of interaction with the user. The user will first provide some info and as a response to the user reply, my bot asks for location using the button object wrapped inside keyboard object as follows:

bot.on('/test', msg => {
  
  let fromId = msg.from.id;
  let firstName = msg.from.first_name;
  let reply = msg.message_id;
  //the bot.keyboard() takes first argument as array of arrays
  let markup = bot.keyboard([[bot.button('location','Send your location')]],"once"); 
  //console.log(markup);
  return bot.sendMessage(fromId, "Send location" , { markup });
});

I cannot figure out where can I put the callback method that will get the location sent by the user. I found out that the "update" event can be listened to. But I guess there is a more convenient way of getting this done. Could you please suggest something on this?

bot.start

TypeError: bot.start is not a function

Help me, I am newbie at all...

Double on server

hii, i think i got some issue,

when i upload my bot on server the output is always double, but when it come to localhost the bot is run normaly...
someone got issue with me?

Community Group

mullwar than you.
You wrapper is great.
What do you think about create telegram group when developers can talk with each other?

pooling vs. polling

Hi, I noticed that your config has a "pooling" option.
Shouldn't this be "polling"?

Hi, help me

/home/ubuntu/workspace/node_modules/telebot/index.js:165
for (var update of data) {
^^
SyntaxError: Unexpected identifier
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 Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/home/ubuntu/workspace/telebot/server.js:1:77)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

sendPhoto with notification disabled throws an error

Using bot.sendPhoto with the notify: false option throws the following error:

_http_outgoing.js:456
    throw new TypeError('First argument must be a string or Buffer');
    ^

TypeError: First argument must be a string or Buffer
    at ClientRequest.OutgoingMessage.write (_http_outgoing.js:456:11)
    at Request.write (/tmp/telebot/node_modules/request/request.js:1387:27)
    at FormData.ondata (stream.js:31:26)
    at emitOne (events.js:96:13)
    at FormData.emit (events.js:188:7)
    at FormData.CombinedStream.write (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:118:8)
    at FormData.CombinedStream._pipeNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:106:8)
    at FormData.CombinedStream._getNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:79:10)
    at FormData.CombinedStream._pipeNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:107:8)
    at FormData.CombinedStream._getNext (/tmp/telebot/node_modules/combined-stream/lib/combined_stream.js:79:10)

I tracked the error down to methods.js#L289 where form gets passed as data instead of form (according to telebot.js#L262). Changing the line to

return this.request(`/${ url }`, form);

will result in the request going through and the photo being send like expected, but will make the tests fail so i'm sure that's not the root cause. Unfortunately, i'm not familiar enough with the lib to pinpoint it myself.

To reproduce:

const TeleBot = require('telebot');
let t = new TeleBot("TOKEN");
t.sendPhoto("CHAT_ID", "https://telegram.org/img/t_logo.png", {
    notify: false
});

I'm using node v6.7.0, npm v3.10.8 & telebot v1.0.6.

Failed to reproduce inlineKeyboard/button example

I checked out the examples at:
https://github.com/mullwar/telebot/blob/master/examples/keyboard.js

but unfortunately, could not get the bot to render an inline keyboard or button.

Env: Mac OS. Telegram Desktop v 1.1.2

e.g.

bot.on('/inlineKeyboard', msg => {

    let replyMarkup = bot.inlineKeyboard([
        [
            bot.inlineButton('callback', {callback: 'this_is_data'}),
            bot.inlineButton('inline', {inline: 'some query'})
        ], [
            bot.inlineButton('url', {url: 'https://telegram.org'})
        ]
    ]);

    return bot.sendMessage(msg.from.id, 'Inline keyboard example.', {replyMarkup});

});

image

== or ==

bot.on('/buttons', msg => {

    let replyMarkup = bot.keyboard([
        [bot.button('contact', 'Your contact'), bot.button('location', 'Your location')],
        ['/back', '/hide']
    ], {resize: true});

    return bot.sendMessage(msg.from.id, 'Button example.', {replyMarkup});

});

image

Question: Shall I activate any option setting in order to allow the bot to reply with buttons/keyboards?
It seems simple and straightforward, but I got stuck.
My other custom commands work just fine.

P.S:
The only time I partially succeeded was the code sample from this issue:
#29 (comment)

bot.on('/testkeys', msg => {
  const chatId = msg.chat.id;

  let markup = bot.keyboard([
      ['hello button']
    ], { resize: true, once: true });

    return bot.sendMessage(chatId, 'Hello :)', { markup });

});

image

Thank you in advance 🍻

is markup only avaliable for one event only?

i wonder is it true that telebot just accept one markup on one event only?
this is work for first markup but dont with other markup on else statement....

for example
bot.on('text', msg =>{
if (msg.text=="yes")
{ let markup = bot.keyboard([
['test yoyow']
], { resize: true})
return bot.sendMessage(
msg.from.id, 'yoyow' ,{ask : 'day', markup, parse: 'html'}
}
else
{
let markup = bot.keyboard([
['test yayai']
], { resize: true})
return bot.sendMessage(
msg.from.id, 'yayai' ,{ask : 'day', markup, parse: 'html'}
}
}
})

return inlineQuery with HTML markup

how to return html markup in inlineQuery?

bot.on('inlineQuery', msg => {

  let query = msg.query;
  console.log(`inline query: ${ query }`);
  // Create a new answer list object
  var answers = bot.answerList(msg.id);

  answers.addArticle({
    id: '121212',
    title: 'What is Function?',
    description: 'huha',
    message_text: '`<a href="aa">a</a>`'
  }, {
    parse: 'html'
  });

  return bot.answerQuery(answers);
});

Instance of Bot

Can u explain me how can I call the connection of the bot in multiple js files?
I have two routes, telegram.js and ask.js that uses the telebot library
I have a connection to the bot in a file:

const TeleBot = require('telebot');
const telegramConstants = require("../../config/config");
const bot = new TeleBot({
    token: telegramConstants.botToken,
    polling: { // Optional. Use polling.
        interval: 60, // Optional. How often check updates (in ms).
        timeout: 0, // Optional. Update polling timeout (0 - short polling).
        limit: 100, // Optional. Limits the number of updates to be retrieved.
        retryTimeout: 1000, // Optional. Reconnecting timeout (in ms).
        allowedUpdates: [] // Optional. List the types of updates you want your bot to receive. Specify an empty list to receive all updates regardless of type.
    }
});

bot.connect();
module.exports = bot;

And I call it in my two js files but it creates a new instance for every call.

sin titulo

Its possible to use one instance of the telebot in my two files?

Name button

Hi,

I would like to change the name of the buttons , so that when the user clicks the button is passed to the BOT button command .

Example

...

bot.on('/buttons', msg => {


  let markup = bot.keyboard([
    [bot.button ('/ex1','/ex1'), bot.button('/ex2', '/ex2')],

...

necessary that the button is called button1 and the command to be sent is /ex1
There is this possibility ?

Thank you

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.