Giter Club home page Giter Club logo

botgram's Introduction

Botgram

Bots are special Telegram users controlled with an HTTP API. Botgram aims to expose the capabilities of this API with a very clear and minimal syntax, so you can create Telegram bots easily.

const botgram = require("botgram")
const bot = botgram("<auth token>")

bot.command("start", "help", (msg, reply) =>
  reply.text("To schedule an alert, do: /alert <seconds> <text>"))

bot.command("alert", (msg, reply, next) => {
  var [ seconds, text ] = msg.args(2)
  if (!seconds.match(/^\d+$/) || !text) return next()

  setTimeout(() => reply.text(text), Number(seconds) * 1000)
})

bot.command((msg, reply) =>
  reply.text("Invalid command."))

Features

  • Simple, intuitive API.
  • Quick setup; just put your auth token and you're in business.
  • Exposes all functionality in the Bot API 2.3.1, including custom keyboards, inline keyboards, force reply, chat actions, deep linking, kicking users, editing messages, notifications...
  • Ability to stream downloads and uploads.
  • Powerful, connect-style message handling and filtering.

Bots API version implemented: December 4, 2016

Install

npm install botgram

Follow the tutorial, take a look at more examples, or consult the documentation.

botgram's People

Contributors

dependabot[bot] avatar libertylocked avatar mildsunrise 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

botgram's Issues

TelegramError: can't use getUpdates method while webhook is active

I accidentally run node-botgram service and api.ai integrations with the same bot token, the service is crash. and when i try to run node-botgram service, i got this message:

TelegramError: getUpdates failed: Conflict: can't use getUpdates method while webhook is active

how do i fixed that?
thanks

Initialize only with App Id and App Hash

Hello everyone,

I hope you're doing well! I'm currently facing some challenges while trying to create a specific use case for a bot. The bot should be able to initialize with only the App Id and App Hash from a Telegram account. Once the code is initialized, it will prompt the user for their phone number and the code sent by Telegram. In some cases, it may also require the user's two-factor authentication password, if applicable.

I was wondering if there is a way to achieve this functionality. Any guidance or suggestions would be greatly appreciated.

Thank you all!

Documentation

Document the API.

  • Tutorial
  • Message object
  • Message handling
  • Reply queues
  • Inline queries
  • Callback queries
  • Global methods

Resume development

Hi. This framework, even though it's unpopular, has become an example to me of how to write code FOR PEOPLE. The ideas of this framework became the basis on which I wrote https://github.com/TRIGONIM/ggram

Now, when I need to write a bot in Js, I find only 2 giants and both are overly complicated and I can't understand why developers love them.

Please resume the development of this framework or please tell me why you stopped it. I'm just starting to use NodeJS and maybe I just don't understand the need for complications in other repositories yet

inlineKeyboard not working

I am trying to implement an inlineKeyboard in my Telegram bot, but keep getting following error:

TelegramError: sendMessage failed: Bad Request: field "inline_keyboard" of the InlineKeyboardMarkup should be an Array of Arrays

I have tried with the example you provided in the docs, but keep getting the same error.

// People who are allowed to manipulate the volume
var ALLOWED_SENDERS = [ 8951984, 5091503, ... ];

bot.command("volumeknob", function (msg, reply, next) {
  reply.inlineKeyboard([
    { text: "↑  Turn up", data: JSON.stringify({ type: "volume", direction: true }) },
    { text: "↓  Turn down", data: JSON.stringify({ type: "volume", direction: false }) },
  ]);
  reply.text("Use the buttons below to modify the volume:");
});

bot.callback(function (query, next) {
  // Try to parse payload data as JSON. If we succeed, and `type` is set
  // to "volume" then the query is for us.
  var data;
  try {
    data = JSON.parse(query.data);
  } catch (e) {
    return next();
  }
  if (data.type !== "volume")
    return next();

  // Check sender is in whitelist
  if (ALLOWED_SENDERS.indexOf(query.from.id) === -1)
    return query.answer({ text: "Permission denied." });
  
  // Turn volume up or down
  if (data.direction) {
    system.volumeUp();
    query.answer();
  } else {
    system.volumeDown();
    query.answer();
  }
});

Inline bot support

Implement the answer method of inline queries, which would complete support for inline bots.

msg.args() is not intuitive

It's weird behavior that the following command:
/cmd

msg.args() returns "" correctly, but when you try to split it, msg.args(2) returns ['']. It should return [], as there are no arguments.

Question: Actively sending messages

What would be the correct approach to implement a personal assistant-like bot that after the /start command waits for an external event (such as a weather update) and notifies the owner's chat? After a server reboot, how can I send pending messages to the owner's chat? Is there some way to save the chat ID?

MYSQL QUERY

First of all I would like to thank you for the beautiful work of the scripts. I need to do an implementation for query in a mysql database (pdo) and show the results by the telegram. Can someone help me ?

Best Regards !

photo upload broken

Using the minimal example at the documentation:

bot.command("send_drawing", function (msg, reply, next) {
  var stream = fs.createReadStream("./drawing.jpg");
  reply.action("upload_photo");
  reply.photo(stream, "My drawing");
});

Replacing the path with my own image produces the following exception:

throw new Error("Invalid file ID");
    ^

Error: Invalid file ID
    at Object.resolveFile (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/model.js:789:11)
    at ReplyQueue.photo (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/reply.js:153:16)
    at Bot.<anonymous> (/Users/twinone/dev/fib-bot/index.js:23:11)
    at Bot.<anonymous> (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/message.js:81:22)
    at HandlerQueue.callHandler (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/message.js:57:29)
    at Bot.<anonymous> (/Users/twinone/dev/fib-bot/bot/state.js:22:9)
    at Bot.<anonymous> (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/message.js:81:22)
    at HandlerQueue.callHandler (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/message.js:57:29)
    at Bot.processMessage (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/message.js:46:15)
    at Bot.processUpdate (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/bot.js:245:10)
    at Array.forEach (native)
    at Bot.<anonymous> (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/bot.js:214:12)
    at handleBody (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/bot.js:153:25)
    at IncomingMessage.<anonymous> (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/bot.js:142:33)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)

Process finished with exit code 1

Also directly passing the path as a string instead of a readable stream has the following error sendPhoto failed: Bad Request: URL host is empty:

events.js:160
      throw er; // Unhandled 'error' event
      ^
TelegramError: sendPhoto failed: Bad Request: URL host is empty
    at TelegramError.Error (native)
    at new TelegramError (/Users/twinone/dev/fib-bot/node_modules/botgram/lib/bot.js:37:20)

Can you reproduce this?

keyboard resize fix

change markup.resize to markup.resize_keyboard in lib/relpy.js 270 and 279 lines

commands

hello, my installation was all ok without errors, but i can run the command /run for other commands i get a error "no command is running" i have tryied the commands cancel ende kill , and restart server but no lucky... any ideas??

thanks in advanced

Question: Error handling

I've been searching through the docs but I can only find something like "all errors are emitted on the bot object".

How can I catch them?
Maybe it's an idea to write a very small sample of error catching so that the process doesn't crash when a network error occurs.

Thanks!

NetworkError: getUpdates failed (after ~24 hours)

Hi, I am running a modified version of shell-bot. I just removed some of the commands and added my own. (I can post the code if needed)

After the bot is running smoothly for some hours (usually 1 day or so) it will stop responding to commands and spam the logs with these errors:

I am using OpenVPN and and a internet connection that restarts itself every 24 which might be the problem I think. Any advice what I would need to change to avoid restarting every 24h via cron?

Thanks!

  name: 'NetworkError',
  stack: 'NetworkError: getUpdates failed: Error: getaddrinfo EAI_AGAIN api.telegram.org:443\n    at new NetworkError (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:20:20)\n    at ClientRequest.handleResponse (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:133:24)\n    at emitOne (events.js:121:20)\n    at ClientRequest.emit (events.js:211:7)\n    at TLSSocket.socketErrorListener (_http_client.js:401:9)\n    at emitOne (events.js:116:13)\n    at TLSSocket.emit (events.js:211:7)\n    at emitErrorNT (internal/streams/destroy.js:66:8)\n    at args.(anonymous function) (/usr/local/lib/nodejs/node-v8.15.0/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)\n    at _combinedTickCallback (internal/process/next_tick.js:139:11)\nWhen calling method getUpdates: { offset: 273312714, timeout: 600 }\n    at Bot.callMethod (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:102:18)\n    at Bot.consumeUpdates (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:201:8)\n    at ontimeout (timers.js:498:11)\n    at tryOnTimeout (timers.js:323:5)\n    at Timer.listOnTimeout (timers.js:290:5)',
  message: 'getUpdates failed: Error: getaddrinfo EAI_AGAIN api.telegram.org:443',
  err: 
   { Error: getaddrinfo EAI_AGAIN api.telegram.org:443
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26)
     errno: 'EAI_AGAIN',
     code: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'api.telegram.org',
     host: 'api.telegram.org',
     port: 443 },
  req: 
   { Error: When calling method getUpdates: { offset: 273312714, timeout: 600 }
    at Bot.callMethod (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:102:18)
    at Bot.consumeUpdates (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:201:8)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
     method: 'getUpdates',
     parameters: { offset: 273312714, timeout: 600 },
     message: 'When calling method getUpdates: { offset: 273312714, timeout: 600 }' } }
Error when updating: { NetworkError: getUpdates failed: Error: getaddrinfo EAI_AGAIN api.telegram.org:443
    at new NetworkError (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:20:20)
    at ClientRequest.handleResponse (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:133:24)
    at emitOne (events.js:121:20)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:401:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:66:8)
    at args.(anonymous function) (/usr/local/lib/nodejs/node-v8.15.0/lib/node_modules/pm2/node_modules/event-loop-inspector/index.js:138:29)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
When calling method getUpdates: { offset: 273312714, timeout: 600 }
    at Bot.callMethod (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:102:18)
    at Bot.consumeUpdates (/home/dietpi/shell-bot/node_modules/botgram/lib/bot.js:201:8)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)

I also checked if I have any webhooks attached to the bot but it does not seem to be the case:
https://api.telegram.org/bot<token>/deleteWebhook
{"ok":true,"result":true,"description":"Webhook is already deleted"}

Question: Replying to callback queries with text

How do i get the bot to reply to callback queries with text?

bot.command("", (msg, reply, cmdNext) => {
bot.callback((query, cbNext) => {
const data = JSON.parse(query.data)
if (data.action === "yes")
bot.text((msg, reply, textNext) => reply.text("You clicked yes"))
})
})

how send a audio/video?

how can i make the bot send an audio file or a video (that already are in telegram servers) to a group?

Using force reply/creating step by step flows

I can't seem to get forceReply to work :/

bot.command('CommandName', (msg, reply) => {
	const { id } = msg.user;
	reply
		.keyboard([['Option1','Option2']])
		.forceReply() //Tried force() | force_reply() | forceReply(true)
		.text(`Would you like option 1 or 2?`)
});

bot.text(function (msg, reply) {
	console.log(msg);
	console.log(msg.reply); //Get undefined, no matter what variation I try
	reply.text(`Bot replying to a forced reply...`);
});

I must be doing something obviously wrong. Does anyone have any pointers?

Or is there any other way to create a step by step conversation flow (where I can hold conversation state between back and forth messages?)


Ps - Cheers for the easy to use library!

Edit - Added javascript in markdown

Support multiple handlers

In some connect style frameworks you can do

function checkAdmin(msg, reply, next) {
    if (msg.from.id === 1) next()
}

bot.command('dangerous_action', checkAdmin, function (msg, reply, next) {
    reply.text('Dangerous action done')
})

This way you can "prefix" handlers with other middleware instead of having to write:

bot.command('dangerous_action', checkAdmin)
bot.command('dangerous_action', function (msg, reply, next) {
    reply.text('Dangerous action done')
})

It would be nice to have this syntax. Can I work on a PR?

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.