Giter Site home page Giter Site logo

telebot.nim's Introduction

telebot.nim

Async Telegram Bot API Client implement in @Nim-Lang

Notes

From version 1.0.0, procs likes newMessage, newPhoto,.. are gone, use sendMessage, sendDocument instead. If you still prefer the old/ugly way to send stuffs, just import telebot/compat for backward compatible

Installation

$ nimble install telebot

Usage

echo bot

import telebot, asyncdispatch, logging, options, strutils
var L = newConsoleLogger(fmtStr="$levelname, [$time] ")
addHandler(L)

# remember to strip your secret key to avoid HTTP error
const API_KEY = strip(slurp("secret.key"))

proc updateHandler(b: Telebot, u: Update): Future[bool] {.async.} =
  if u.message.isNil:
    # return true will make bot stop process other callbacks
    return true
  var response = u.message
  if response.text.len > 0:
    let text = response.text
    discard await b.sendMessage(response.chat.id, text, parseMode = "markdown", disableNotification = true, replyParameters = ReplyParameters(messageId: response.messageId))

let bot = newTeleBot(API_KEY)
bot.onUpdate(updateHandler)
bot.poll(timeout=300)

send local photo

import telebot, asyncdispatch, options, logging, strutils

# remember to strip your secret key to avoid HTTP error
const API_KEY = strip(slurp("secret.key"))

proc updateHandler(bot: TeleBot, update: Update): Future[bool] {.async.} =
  discard await bot.sendPhoto(response.chat.id, "file:///path/to/photo.jpg")

let bot = newTeleBot(API_KEY)
bot.onUpdate(updateHandler)
bot.poll(timeout=300)

For more information please refer to official Telegram Bot API page

telebot.nim's People

Contributors

altfoxie avatar ba0f3 avatar baalajimaestro avatar dadadani avatar ethosa avatar facorazza avatar hamidb80 avatar ire4ever1190 avatar juancarlospaco avatar keshon avatar lompik avatar michal-szczepaniak avatar retrodynen avatar ringabout avatar thisago avatar watchcat avatar weebnetsu avatar yglukhov avatar zedeus 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

telebot.nim's Issues

sam.nim(199, 10) `n.mapper.tokens[n.pos].kind == JSMN_OBJECT` assertionDefect

Bot randomly starts to crash - change in bot API?

I'm forced to rerun the bot with clean=true to get rid of the message queue, it then works for several more days until the same thing happens. 


Error: unhandled exception: /home/zack/.nimble/pkgs/sam-0.1.17/sam.nim(199, 10) `n.mapper.tokens[n.pos].kind == JSMN_OBJECT`  
Async traceback: 
 /home/zack/.nimble/pkgs/cligen-1.5.19/cligen.nim(788)                       banner 
 /home/zack/.nimble/pkgs/cligen-1.5.19/cligen.nim(720)                       multiSubs 
 /home/zack/.nimble/pkgs/cligen-1.5.19/cligen.nim(802)                       multi 
 /home/zack/.nimble/pkgs/cligen-1.5.19/cligen.nim(720)                       dispatchstart 
 /med/sync/MiscDocs/mbot/banner.nim(103)                                     tgmain 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/api.nim(1170)        poll 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/pure/asyncdispatch.nim(1961) waitFor 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/pure/asyncdispatch.nim(1653) poll 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/pure/asyncdispatch.nim(1394) runOnce 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/pure/asyncdispatch.nim(234)  processPendingCallbacks 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/pure/asyncmacro.nim(28)      loopNimAsyncContinue 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/api.nim(1164)        loopIter 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/utils.nim(97)        unmarshal 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/utils.nim(176)       toOption 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/utils.nim(99)        unmarshal 
 /home/zack/.nimble/pkgs/telebot-1.0.11/telebot/private/utils.nim(107)       unmarshal 
 /home/zack/.nimble/pkgs/sam-0.1.17/sam.nim(199)                             [] 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/system/assertions.nim(38)    failedAssertImpl 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/system/assertions.nim(28)    raiseAssert 
 /home/zack/.choosenim/toolchains/nim-1.6.0/lib/system/fatal.nim(53)         sysFatal 
Exception message: /home/zack/.nimble/pkgs/sam-0.1.17/sam.nim(199, 10) `n.mapper.tokens[n.pos].kind == JSMN_OBJECT`  
[AssertionDefect]

Message response can be very sluggish

Hello :)

So I've started moving my bot from Python to Nim, and for the most part there are no problems with the move, although, the response time often takes half a second more (or more) to send a reply, compared to the Python version... The Python version uses pyTelegramBotAPI

Now this is of course nothing massive, but that speed difference can sometimes be quite noticeable... Is this a Nim thing? Or maybe I'm compiling it wrong? Or is there something in the module slowing it down?

`umarshal` function tries to extract `type` field for `InlineKeyboardMarkup` from corresponding JSON, which is not available

Hey,
I just found out that example/inline_query_with_input_message_content.nim does not work.

I followed the stack trace which was:

>>>  key not found: type
Async traceback:
  \azmmonak\bot\src\main.nim(417)             main
  \telebot\src\telebot\private\api.nim(1185)  poll
  \toolchains\nim-1.6.2\lib\pure\asyncdispatch.nim(1961)     waitFor
  \toolchains\nim-1.6.2\lib\pure\asyncdispatch.nim(1653)     poll
  \toolchains\nim-1.6.2\lib\pure\asyncdispatch.nim(419)      runOnce
  \toolchains\nim-1.6.2\lib\pure\asyncdispatch.nim(234)      processPendingCallbacks
  \toolchains\nim-1.6.2\lib\pure\asyncmacro.nim(28)          loopNimAsyncContinue
  \telebot\src\telebot\private\api.nim(1179)  loopIter
  \telebot\src\telebot\private\utils.nim(100) unmarshal
  \telebot\src\telebot\private\utils.nim(213) toOption
  \telebot\src\telebot\private\utils.nim(184) unref
  \telebot\src\telebot\private\utils.nim(100) unmarshal
  \telebot\src\telebot\private\utils.nim(199) toOption
  \telebot\src\telebot\private\utils.nim(100) unmarshal
  \telebot\src\telebot\private\utils.nim(213) toOption
  \telebot\src\telebot\private\utils.nim(184) unref
  \telebot\src\telebot\private\utils.nim(110) unmarshal
  \toolchains\nim-1.6.2\lib\pure\json.nim(517)               []
  \toolchains\nim-1.6.2\lib\pure\collections\tables.nim(246) []
  \toolchains\nim-1.6.2\lib\pure\collections\tables.nim(234) raiseKeyError
Exception message: key not found: type

and I put some lines for logging after this line

debugEcho name," >> ", value.type, " :: ", jsonKey, " == ", typeof result
debugecho "JSON||", n

as I try to click on the inline button, the last thing that is logged is:

type >> KeyboardKind :: type == InlineKeyboardMarkup:ObjectType
JSON||{"inline_keyboard":[[{"text":"xxx","callback_data":"/t6"}]]}

it looks like the unmarshal function tries to get type field from that JSON

it compiles well but vscode can't find import

image

nim.nimble:

# Package

version       = "0.2.0"
author        = "fulcanelly"
description   = "A new awesome nimble package"
license       = "MIT"
srcDir        = "src"
bin           = @["nim"]


requires "nim >= 1.4.2"
requires "telebot"

nim.cfg:

threads: on
gc: arc
d:ssl

Breaks on devel

/home/user/.nimble/pkgs/telebot-0.4.1/telebot/webhook.nim(31, 65) Error: type mismatch: got <nil> but expected 'string'
stack trace: (most recent call last)
build_nim_telegram_bot.nims(7)
lib/system/nimscript.nim(237) exec
lib/system/nimscript.nim(237, 7) Error: unhandled exception: FAILED: nim c -d:release -d:ssl --app:console --opt:size --out:build/nim_telegram_bot src/nim_telegram_bot.nim

[user@server nim-telegram-bot]$ nim --version
Nim Compiler Version 0.18.1 [Linux: amd64]
Compiled at 2018-08-20
Copyright (c) 2006-2018 by Andreas Rumpf

active boot switches: -d:release

[user@server nim-telegram-bot]$ choosenim devel
      Info: Version #devel already selected

https://github.com/ba0f3/telebot.nim/blob/master/telebot/webhook.nim#L31

Is about the string being nil.

Error: cannot open 'tempfile'

Looks like tempfile, which is referenced in telbot.nim doesn't exist in the nim standard library, isn't a dependency in your .nimble file, and actually doesn't seem to be used. Could we just remove that reference?

Deleting messages?

Is it possible to delete message? i tried to use deleteMessage but it caused whole bot to freeze and nothing more.

Compatibility with Nim 1.2.x

It seems that the recent changes in this repo broke our Nim 1.2.x CIs with the following error:

telebot/private/api.nim(895, 34) Error: undeclared identifier: 'endpoint'

Error compiling inline_query_with_input_message_content example

Example examples/inline_query_with_input_message_content.nim cannot be compiled


throwing error for this line :

Error: type mismatch: got <TeleBot, proc (b: TeleBot, u: InlineQuery): Future[system.void]{.gcsafe, locks: <unknown>.}>
but expected one of:
proc onInlineQuery(b: TeleBot; cb: InlineQueryCallback)
  first type mismatch at position: 2
  required type for cb: InlineQueryCallback
  but expression 'inlineHandler' is of type: proc (b: TeleBot, u: InlineQuery): Future[system.void]{.gcsafe, locks: <unknown>.}

expression: onInlineQuery(bot, inlineHandler)

Command(s) with '@' bot username does not ignore other bot username.

My bot username is @XCosmosBot. When i typed command with other bot username, my bot still respond. eg: "/start@XXXBot" it should only respond to XXXBot, but my bot still respond too. Second, command must be in the first order of a message instead of catching command in every message.

gambar

telebot breaks nim CI

/cc @ba0f3

shouldn't this problem have been caught by this package's own CI? (I don't have full context); after fixing this please revert nim-lang/Nim#17860

https://github.com/nim-lang/Nim/pull/17777/checks?check_run_id=2440887670

PASS: [28/35] strslice c                                                   ( 1.51 sec)
  FAIL: telebot c
  Test "telebot" in category "nimble-packages"
  Failure: reBuildFailed
  nim c -o:tbot -r src/telebot.nim
  Hint: used config file '/home/runner/work/Nim/Nim/config/nim.cfg' [Conf]�
  Hint: used config file '/home/runner/work/Nim/Nim/config/config.nims' [Conf]�
  Hint: used config file '/home/runner/work/Nim/Nim/pkgstemp/telebot/nim.cfg' [Conf]�
  ...................................................
  /home/runner/work/Nim/Nim/pkgstemp/telebot/src/telebot/private/types.nim(1, 8) Warning: imported and not used: 'asyncdispatch' [UnusedImport]�
  .........
  /home/runner/work/Nim/Nim/pkgstemp/telebot/src/telebot/private/utils.nim(56, 20) Warning: Deprecated since v1.5; Use auto instead.; any is deprecated [Deprecated]�
  ...
  /home/runner/work/Nim/Nim/pkgstemp/telebot/src/telebot/private/api.nim(319, 158) template/generic instantiation of `async` from here
  /home/runner/work/Nim/Nim/pkgstemp/telebot/src/telebot/private/api.nim(332, 9) Error: type mismatch: got <MultipartData, string, int>
  but expected one of: 
  proc `[]=`(headers: HttpHeaders; key, value: string)
    first type mismatch at position: 0
  proc `[]=`(headers: HttpHeaders; key: string; value: seq[string])
    first type mismatch at position: 0
  proc `[]=`(p: MultipartData; name, content: string)
    first type mismatch at position: 0
  proc `[]=`(p: MultipartData; name: string;
             file: tuple[name, contentType, content: string])
    first type mismatch at position: 0
  proc `[]=`(s: var string; i: BackwardsIndex; x: char)
    first type mismatch at position: 0
  proc `[]=`(t: StringTableRef; key, val: string)
    first type mismatch at position: 0
  proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S)
    first type mismatch at position: 0
  proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V];
                                    b: openArray[T])
    first type mismatch at position: 0
  proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T)
    first type mismatch at position: 0
  proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string)
    first type mismatch at position: 0
  proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T])
    first type mismatch at position: 0
  proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T)
    first type mismatch at position: 0
  template `[]=`(s: string; i: int; val: char)
    first type mismatch at position: 0
  
  expression: `[]=`(data, "max_tip_amount", maxTipAmount)�
  
  PASS: [30/35] tensordsl c                                                  ( 2.85 sec)

Broken example and possibly broken InlineKeyBoardButton

I tried the example mentioned here

And everytime with every installation of Nim 1.6.4 or master, i am able to replicate

Exception message: Bad Request: can't parse reply keyboard markup JSON object

There is no particular OS that i have found to work. I have tried multiple OS to confirm this issue.

answerInlineQuery don't support cyrillic characters in title and content

issue in title.
code:

proc inlineHandler(b: Telebot, u: InlineQuery) {.async.} =
  var res: InlineQueryResultArticle
  res.kind = "article"
  res.title = "тест"
  res.id = "1"
  res.inputMessageContent = InputTextMessageContent("тест").some
  var results: seq[InlineQueryResultArticle]
  results.add(res)
  discard waitFor b.answerInlineQuery(u.id, results)

getChatMember doesn't show full information

code-snippet-

   
proc canBotPromote*(b: TeleBot, m: Message): Future[bool] {.async.} =
    let bot = await b.getMe()
    let botChat = await getChatMember(b, intToStr(m.chat.id.int), bot.id)
    echo botChat
    if botChat.canPromoteMebers.isSome:
        return botChat.canPromoteMebers.get

Expect output: true
Got output: false
echo BotChat: (user: (id: 667777388, isBot: true, firstName: "BullyBot", lastName: None[string], username: Some("bullygodbot"), languageCode: None[string]), status: "administrator", untilDate: None[int], canBeEdited: Some(false), canChangeInfo: Some(true), canPostMessages: None[bool], canEditMessages: None[bool], canDeleteMessages: Some(true), canInviteUsers: Some(true), canRestrictMembers: Some(true), canPinMessages: Some(true), canPromoteMebers: None[bool], isMember: None[bool], canSendMessages: None[bool], canSendMediaMessages: None[bool], canSendOtherMessages: None[bool], canAddWebPagePreviews: None[bool])

Tested url -
https://api.telegram.org/botsecret:secret/getChatMember?chat_id=-1001262378051&user_id=667777388
Got output:
{"ok":true,"result":{"user":{"id":667777388,"is_bot":true,"first_name":"BullyBot","username":"bullygodbot"},"status":"administrator","can_be_edited":false,"can_change_info":true,"can_delete_messages":true,"can_invite_users":true,"can_restrict_members":true,"can_pin_messages":true,"can_promote_members":true}}

Issue with oneTimeKeyboard in ReplyKeyboardMarkup. Keyboard not hiding after clicking on the button.

I used the webapp example currently available in the examples but added the oneTimeKeyboard option to the ReplyKeyboardMarkup. However, after trying different approaches, my attempts have been unsuccessful.

import telebot, asyncdispatch, logging, options
from strutils import strip

var L = newConsoleLogger()
addHandler(L)

const API_KEY = slurp("secret.key").strip()

proc updateHandler(b: Telebot, u: Update): Future[bool] {.gcsafe, async.} =
  var response = u.message.get
  if response.text.isSome:
    let text = response.text.get
    var google = KeyboardButton(text: "Search the web", webApp: some WebAppInfo(url: "https://google.com"))

    let replyMarkup = ReplyKeyboardMarkup(kind: kReplyKeyboardMarkup, *oneTimeKeyboard: some(true)*, keyboard: @[@[google]])
# I also tried adding the bool statement as replyMarkup.oneTimeKeyboard = some(true)
    discard await b.sendMessage(response.chat.id, text, replyMarkup = replyMarkup)

when isMainModule:
  let bot = newTeleBot(API_KEY)

  bot.onUpdate(updateHandler)
  bot.poll(timeout=300)

According to the telgram bot documentation (https://core.telegram.org/bots/api/#replykeyboardmarkup), this option should hide the button as soon as it is clicked. However it is not working.
The Type ReplyKeyboardMarkup includes this option... I'm not sure if I'm making a mistake or did something wrong. I've also tried with every available option in the KeyboardButton, including location and contacts (var google = KeyboardButton(text: "Search the web", requestLocation:some(true)) instead of the code above in the same line.). The code otherwise works flawlessly and prompts a google site or requests a contact or my location; however, upon closing the app, the keyboard button still remains visible and does not hide.

I'm using telebot's latest code and nim 1.7.1
Thank you for your awesome work with this!

Error while trying to compile example

I installed telebot using nimble and was trying to compile example but i'm getting this error:

../.nimble/pkgs/telebot-0.5.7.2/telebot/utils.nim(189, 21) template/generic instantiation from here
../.nimble/pkgs/telebot-0.5.7.2/telebot/utils.nim(109, 19) template/generic instantiation from here
../.nimble/pkgs/telebot-0.5.7.2/telebot/utils.nim(172, 23) template/generic instantiation from here
../.nimble/pkgs/telebot-0.5.7.2/telebot/utils.nim(107, 12) Error: undeclared field: 'data'

nim version is 0.19.4

How to handle WebApp data sent by the client

I have got an HTML where when a button is clicked, it sends data to the bot, it uses an updateHandler because I thought it could handle every update, but it is not going there

RangeError when I start program

Hello!
When i start my program with any token - RangeError
Program:

import telebot, asyncdispatch, logging, options, os
const API_KEY = ""

proc updateHandler(b: Telebot, u: Update) {.async.} =
  var response = u.message.get
  if response.text.isSome:
    let
      text = response.text.get
    var message = newMessage(response.chat.id, text)
    message.disableNotification = true
    message.replyToMessageId = response.messageId
    message.parseMode = "markdown"
    discard await b.send(message)

let bot = newTeleBot(API_KEY)
bot.onUpdate(updateHandler)
bot.poll(timeout=300)

Error:
main.nim(18)             main
api.nim(652)             poll
utils.nim(94)            unmarshal
utils.nim(155)           toOption
utils.nim(96)            unmarshal
system.nim(1280)         unmarshal
system.nim(2924)         sysFatal
Error: unhandled exception: value out of range: -1001457161642 [RangeError]

Shouldn't update callbacks always be called?

Currently any onUpdate callbacks aren't called if the message has a command or an inline query. This kind of breaks my use case for this library, because there are certain things I want to do for every update that comes in. It would be a pretty simple fix and I could get a PR in if you want.

error while compiling

i got this error, why?

../.nimble/pkgs/telebot-0.6.0/telebot/utils.nim(187, 24) Error: undeclared identifier: 'newJNull'

nim CI fails with this package

hi @ba0f3 nim CI fails with this package
happened in this PR nim-lang/Nim#13812
https://dev.azure.com/nim-lang/255dfe86-e590-40bb-a8a2-3c0295ebdeb1/_apis/build/builds/3804/logs/76

020-03-31T04:11:08.8084082Z PASS: https://github.com/nitely/nim-strunicode C                   (16.36 sec)
2020-03-31T04:11:08.8084648Z FAIL: https://github.com/ba0f3/telebot.nim C
2020-03-31T04:11:08.8085215Z Test "https://github.com/ba0f3/telebot.nim" in category "nimble-packages"
2020-03-31T04:11:08.8085666Z Failure: reBuildFailed
2020-03-31T04:11:08.8085976Z package test failed
2020-03-31T04:11:08.8086376Z $ nim c -o:tbot --oldgensym:on -r telebot.nim
2020-03-31T04:11:08.8086809Z Hint: used config file 'd:\a\1\s\config\nim.cfg' [Conf]
2020-03-31T04:11:08.8087311Z Hint: used config file 'd:\a\1\s\config\config.nims' [Conf]
2020-03-31T04:11:08.8088003Z Hint: used config file 'd:\a\1\s\pkgstemp\telebot\nim.cfg' [Conf]
2020-03-31T04:11:08.8088688Z Hint: system [Processing]
2020-03-31T04:11:08.8089013Z Hint: widestrs [Processing]
2020-03-31T04:11:08.8089517Z Hint: io [Processing]
2020-03-31T04:11:08.8089889Z Hint: telebot [Processing]
2020-03-31T04:11:08.8090284Z Error: cannot open 'telebot.nim'
2020-03-31T04:11:08.8090583Z 
2020-03-31T04:13:36.5527784Z PASS: https://github.com/euantorano/tempdir.nim C                  ( 2.20 sec)
2020-03-31T04:13:36.5528938Z PASS: https://[email protected]/krux02/tensordslnim.git C       ( 4.43 sec)
2020-03-31T04:13:36.5529490Z PASS: https://github.com/GULPF/tiny_sqlite C                       ( 4.74 sec)
2020-03-31T04:13:36.5530028Z PASS: https://github.com/nitely/nim-unicodedb C                    (68.16 sec)
2020-03-31T04:13:36.5530540Z PASS: https://github.com/nitely/nim-unicodeplus C                  (35.15 sec)
2020-03-31T04:13:36.5531014Z PASS: https://github.com/technicallyagd/unpack C                   ( 5.96 sec)
2020-03-31T04:13:36.5531543Z PASS: https://github.com/zevv/with C                               ( 5.45 sec)
2020-03-31T04:13:36.5532202Z PASS: https://github.com/treeform/ws C                             ( 5.74 sec)
2020-03-31T04:13:36.5532996Z PASS: https://github.com/flyx/NimYAML C                            ( 2.93 sec)
2020-03-31T04:13:36.5533531Z PASS: https://github.com/zero-functional/zero-functional C         (12.67 sec)
2020-03-31T04:13:36.5534014Z FAIL: PackageFileParsed C
2020-03-31T04:13:36.5534502Z Test "PackageFileParsed" in category "nimble-packages"
2020-03-31T04:13:36.5534883Z Failure: reBuildFailed

Telebot no longer work

/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/api.nim(706) poll
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1868) waitFor
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1562) poll
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1328) runOnce
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(210) processPendingCallbacks
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncmacro.nim(34) loopNimAsyncContinue
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/api.nim(699) loopIter
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79) unmarshal
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(155) toOption
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79) unmarshal
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(155) toOption
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79) unmarshal
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(159) toOption
/home/foidbgen/.nimble/pkgs/sam-0.1.10/sam.nim(230) toStr
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/assertions.nim(27) failedAssertImpl
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/assertions.nim(20) raiseAssert
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/fatal.nim(39) sysFatal
[[reraised from:
/home/foidbgen/nim-playground/bot.nim(761) bot
/home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/api.nim(706) poll
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1870) waitFor
/home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncfutures.nim(374) read
]]
Error: unhandled exception: /home/foidbgen/.nimble/pkgs/sam-0.1.10/sam.nim(230, 10) `node.mapper.tokens[node.pos].kind == JSMN_STRING` 
Async traceback:
  /home/foidbgen/nim-playground/bot.nim(761)                                       bot
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/api.nim(706)                   poll
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1868) waitFor
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1562) poll
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(1328) runOnce
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncdispatch.nim(210)  processPendingCallbacks
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/pure/asyncmacro.nim(34)      loopNimAsyncContinue
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/api.nim(699)                   loopIter
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79)                  unmarshal
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(155)                 toOption
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79)                  unmarshal
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(155)                 toOption
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(79)                  unmarshal
  /home/foidbgen/.nimble/pkgs/telebot-0.6.9/telebot/utils.nim(159)                 toOption
  /home/foidbgen/.nimble/pkgs/sam-0.1.10/sam.nim(230)                              toStr
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/assertions.nim(27)    failedAssertImpl
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/assertions.nim(20)    raiseAssert
  /home/foidbgen/.choosenim/toolchains/nim-0.20.2/lib/system/fatal.nim(39)         sysFatal
Exception message: /home/foidbgen/.nimble/pkgs/sam-0.1.10/sam.nim(230, 10) `node.mapper.tokens[node.pos].kind == JSMN_STRING` 
Exception type: [AssertionError]

Location must be float

Location works Ok, but its longitude and latitude must be float, at least rounded floats.

import telebot, asyncdispatch, options

const API_KEY = ""

proc geoHandler(bot: TeleBot): CommandCallback =
  proc cb(e: Command) {.async.} =
    let message = newLocation(e.message.chat.id, longitude=42.9, latitude=42.9)
    discard await bot.send(message)
  result = cb

let bot = newTeleBot(API_KEY)
bot.onCommand("geo", geoHandler(bot))
bot.poll(666)

Produces the error:

nim_telegram_bot.nim(234, 22) template/generic instantiation from here
nim_telegram_bot.nim(145, 23) template/generic instantiation from here
nim_telegram_bot.nim(150, 31) Error: type mismatch: got <longitude: float64, latitude: float64>
but expected one of: 
proc newLocation(chatId: int; latitude: int; longitude: int): LocationObject

expression: newLocation(longitude = 42.9, latitude = 42.9)

Change:

let message = newLocation(e.message.chat.id, longitude=42.9, latitude=42.9)

To:

let message = newLocation(e.message.chat.id, longitude=42, latitude=42)

And it works.

https://core.telegram.org/bots/api#location

0.9 on Latitude or Longitude is a lot of terrain.

Seems kinda easy to fix since change type from int to float. Feel free to use the example code.

Thanks for the epic work on this framework ❕ 😺

Compile issue on latest telebot

/telebot/telebot/webhook.nim(66, 33) template/generic instantiation of async from here
.choosenim/toolchains/nim-#devel/lib/pure/asyncmacro.nim(272, 31) Error: 'callbackIter' is not GC-safe as it calls 'handleUpdate'

Invalid http version

DEBUG, [21:01:00] Making request to https://api.telegram.org/bot[API_KEY_OMITTED]
/getUpdates
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1507)  waitFor
asyncdispatch.nim(1511)  poll
asyncdispatch.nim(1277)  runOnce
asyncdispatch.nim(183)   processPendingCallbacks
asyncmacro.nim(34)       parseResponse_continue
httpclient.nim(1040)     parseResponseIter
httpclient.nim(226)      httpError
[[reraised from:
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1507)  waitFor
asyncdispatch.nim(1511)  poll
asyncdispatch.nim(1277)  runOnce
asyncdispatch.nim(183)   processPendingCallbacks
asyncmacro.nim(34)       requestAux_continue
asyncmacro.nim           requestAuxIter
asyncfutures.nim(304)    read
]]
[[reraised from:
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1507)  waitFor
asyncdispatch.nim(1511)  poll
asyncdispatch.nim(1277)  runOnce
asyncdispatch.nim(183)   processPendingCallbacks
asyncmacro.nim(34)       post_continue
asyncmacro.nim           postIter
asyncfutures.nim(304)    read
]]
[[reraised from:
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1507)  waitFor
asyncdispatch.nim(1511)  poll
asyncdispatch.nim(1277)  runOnce
asyncdispatch.nim(183)   processPendingCallbacks
asyncmacro.nim(34)       makeRequest_continue
utils.nim(56)            makeRequestIter
asyncfutures.nim(304)    read
]]
[[reraised from:
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1507)  waitFor
asyncdispatch.nim(1511)  poll
asyncdispatch.nim(1277)  runOnce
asyncdispatch.nim(183)   processPendingCallbacks
asyncmacro.nim(34)       getUpdates_continue
api.nim(233)             getUpdatesIter
asyncfutures.nim(304)    read
]]
[[reraised from:
echo.nim(39)             echo
api.nim(268)             poll
asyncdispatch.nim(1649)  waitFor
asyncfutures.nim(304)    read
]]
Error: unhandled exception: invalid http version, 0x10fe26210"<html>"
Async traceback:
  echo.nim(39)            echo
  api.nim(268)            poll
  asyncdispatch.nim(1507) waitFor
  asyncdispatch.nim(1511) poll
    ## Processes asynchronous completion events
  asyncdispatch.nim(1277) runOnce
  asyncdispatch.nim(183)  processPendingCallbacks
    ## Executes pending callbacks
  asyncmacro.nim(34)      parseResponse_continue
    ## Resumes an async procedure
  httpclient.nim(1040)    parseResponseIter
  httpclient.nim(226)     httpError
  #[
    echo.nim(39)            echo
    api.nim(268)            poll
    asyncdispatch.nim(1507) waitFor
    asyncdispatch.nim(1511) poll
      ## Processes asynchronous completion events
    asyncdispatch.nim(1277) runOnce
    asyncdispatch.nim(183)  processPendingCallbacks
      ## Executes pending callbacks
    asyncmacro.nim(34)      requestAux_continue
      ## Resumes an async procedure
    asyncmacro.nim(0)       requestAuxIter
    asyncfutures.nim(304)   read
  ]#
  #[
    echo.nim(39)            echo
    api.nim(268)            poll
    asyncdispatch.nim(1507) waitFor
    asyncdispatch.nim(1511) poll
      ## Processes asynchronous completion events
    asyncdispatch.nim(1277) runOnce
    asyncdispatch.nim(183)  processPendingCallbacks
      ## Executes pending callbacks
    asyncmacro.nim(34)      post_continue
      ## Resumes an async procedure
    asyncmacro.nim(0)       postIter
    asyncfutures.nim(304)   read
  ]#
  #[
    echo.nim(39)            echo
    api.nim(268)            poll
    asyncdispatch.nim(1507) waitFor
    asyncdispatch.nim(1511) poll
      ## Processes asynchronous completion events
    asyncdispatch.nim(1277) runOnce
    asyncdispatch.nim(183)  processPendingCallbacks
      ## Executes pending callbacks
    asyncmacro.nim(34)      makeRequest_continue
      ## Resumes an async procedure
    utils.nim(56)           makeRequestIter
    asyncfutures.nim(304)   read
  ]#
  #[
    echo.nim(39)            echo
    api.nim(268)            poll
    asyncdispatch.nim(1507) waitFor
    asyncdispatch.nim(1511) poll
      ## Processes asynchronous completion events
    asyncdispatch.nim(1277) runOnce
    asyncdispatch.nim(183)  processPendingCallbacks
      ## Executes pending callbacks
    asyncmacro.nim(34)      getUpdates_continue
      ## Resumes an async procedure
    api.nim(233)            getUpdatesIter
    asyncfutures.nim(304)   read
  ]#
Exception message: invalid http version, 0x10fe26210"<html>"
Exception type: [ProtocolError]

Command with arguments

How I can make a command with arguments? I mean example /help command. I want it to detect an argument and execute another action after typing such an example command rather than after typing /help.

Doesn't work with nim devel

echo bot example from the readme doesn't work with nim devel (3bc625aff1664eb4206ae90d0a132c8f717e651d), because it seems procName is broken in async functions. Here's the log from the bot:

DEBUG, [11:05:40] Making request to https://api.telegram.org/bot<MY_TOKEN>/getMeIter_OOZOOZOnimbleZpkgsZtelebot4549O48O55Ztelebot_5418
DEBUG, [11:05:40] Unable to fetch my info 404 Not Found
Async traceback:
...

As seen from the log above the url ends with getMeIter_OOZOOZOnimbleZpkgsZtelebot4549O48O55Ztelebot_5418 instead of getMe.

InlineKeyboard url field should be optional

Got exception ref 0x1090524c8 --> [parent = nil,
name = 0x108e3a730"IOError",
msg = 0x108f188c8"Bad Request: can't parse inline keyboard button: Field \"url\" must be of type String"

The error happened when I didn't initialize the url field of the button. The docs says it's optional.

setMyCommands compiler error

First of all English is not my mother language, so...

To reproduce:

import telebot

const API_TOKEN = "token"

let command = telebot.BotCommand(command: "command", description: "Return you command")

let bot = newTeleBot(API_TOKEN)
discard bot.setMyCommands(@[command])

first error (i found it mb a compiller bug)

PS G:\Programming\Languages\Nim\HelloTwo> nim r -d:ssl .\main.nim
Hint: used config file 'G:\Programming\nim\config\nim.cfg' [Conf]
Hint: used config file 'G:\Programming\nim\config\config.nims' [Conf]
.............................................................
G:\Programming\Languages\Nim\HelloTwo\main.nim(11, 12) template/generic instantiation of `setMyCommands` from here
C:\Users\nirn2\.nimble\pkgs\telebot-1.0.9\telebot\private\api.nim(1002, 7) Error: redefinition of 'json'; previous declaration here: C:\Users\nirn2\.nimble\pkgs\telebot-1.0.9\telebot\private\api.nim(998, 7)
PS G:\Programming\Languages\Nim\HelloTwo>

Well, small fix setMyCommands json's variables names:

proc setMyCommands*(b: TeleBot, commands: seq[BotCommand], scope = BotCommandScopeDefault, languageCode = ""): Future[bool] {.async.} =
  var data = newMultipartData()
  var json  = ""
  marshal(commands, json)
  data["commands"] = json

  var json = ""
  marshal(scope, json)
  data["scope"] = json

  if languageCode.len != 0:
    data["language_code"] = languageCode

  let res = await makeRequest(b, procName, data)
  result = res.toBool

To

proc setMyCommands*(b: TeleBot, commands: seq[BotCommand], scope = BotCommandScopeDefault, languageCode = ""): Future[bool] {.async.} =
var data = newMultipartData()
var jsonCommands  = ""
marshal(commands, jsonCommands)
data["commands"] = jsonCommands

var jsonScope = ""
marshal(scope, jsonScope)
data["scope"] = jsonScope

if languageCode.len != 0:
  data["language_code"] = languageCode

let res = await makeRequest(b, procName, data)
result = res.toBool

And now we have another compiller error

PS G:\Programming\Languages\Nim\HelloTwo> nim r -d:ssl .\main.nim
Hint: used config file 'G:\Programming\nim\config\nim.cfg' [Conf]
Hint: used config file 'G:\Programming\nim\config\config.nims' [Conf]
.............................................................
G:\Programming\Languages\Nim\HelloTwo\main.nim(8, 12) template/generic instantiation of `setMyCommands` from here
C:\Users\nirn2\.nimble\pkgs\telebot-1.0.9\telebot\private\api.nim(1003, 10) Error: type mismatch: got <type BotCommandScopeDefault, string>
but expected one of:
proc marshal[T](t: T; s: var string)
first type mismatch at position: 1
required type for t: T
but expression 'scope' is of type: type BotCommandScopeDefault

expression: marshal(scope, jsonScope)
PS G:\Programming\Languages\Nim\HelloTwo>

I'am new in Nim and i don't know what can i do with this.

nim version

PS G:\Programming\Languages\Nim\HelloTwo> nim --version
Nim Compiler Version 1.4.8 [Windows: amd64]
Compiled at 2021-05-25
Copyright (c) 2006-2021 by Andreas Rumpf

active boot switches: -d:release
PS G:\Programming\Languages\Nim\HelloTwo>

Error when compiling Echo Bot example

Code Used:
https://github.com/ba0f3/telebot.nim#echo-bot

Command Used:
nim c -d:ssl echo.nim

Output:

C:\Users\User\Desktop\Nim\echo.nim(140, 4) Error: type mismatch: got <TeleBot, proc (b: TeleBot, u: Update):
Future[system.bool]{.locks: <unknown>.}>
but expected one of:
proc onUpdate(b: TeleBot; cb: UpdateCallback)
  first type mismatch at position: 2
  required type for cb: UpdateCallback
  but expression 'updateHandler' is of type: proc (b: TeleBot, u: Update): Future[system.bool]{.locks: <unknown>.}
  Pragma mismatch: got '{..}', but expected '{.gcsafe.}'.
  This expression is not GC-safe. Annotate the proc with {.gcsafe.} to get extended error information.

sharing contact info causes error from `sam` module

Hey,

I just figured it out that sharing contact info causes node.mapper.tokens[node.pos].kind == JSMN_STRING to fail. [from toStr function in \sam-0.1.17\sam.nim(240, 10)]

the value of node.mapper.tokens[node.pos].kind is JSMN_PRIMITIVE.

tested on telebot 1.0.12
nim 1.6.2

Getting id of just sent message

I want to get id of message i just sent and then edit it. How can i do that? For editing message i guess i should use editMessageText but bot.send is discarded in every example so i'm confused

stripping API keys

If the API key is saved in a file with a newline, the sample echo bot will break at runtime.

I think it would be nice to add a bit of robustness by making the example code

import telebot, asyncdispatch, logging, options, std/strutils

const API_KEY = strip(slurp("secret.key")))

(or maybe add a convenience strip() directly on newTeleBot*()?)

How can I catch an unknown command?

I'd like to use a proc like this one in events.nim:

proc onUnknownCommand*(b: TeleBot, cb: CommandCallback) =
  b.commandCallbacks["-"].add(cb)

but I'm not sure how things are handled so I'm asking for help.

Perhaps, this new proc is not necessary. However, we must be sure not to catch commands already processed with onCommand().

With 5.0 API release echo example is not working

Hi it seems new 5.0 API release broke sendMethod proc (maybe due to entities arg?) in your examples. Here is a compiler error for echo_bot example:

C:\Temp\telebot.nim\examples\echo_bot.nim(15, 20) Error: type mismatch: got <TeleBot, int64, string, parseMode: string, disableNotification: bool, replyToMessageId: int>
but expected one of:
proc sendMessage(b: TeleBot; chatId: int64; text: string; parseMode = "";
                 entities: seq[MessageEntity]; disableWebPagePreview = false;
                 disableNotification = false; replyToMessageId = 0;
                 allowSendingWithoutReply = false;
                 replyMarkup: KeyboardMarkup = nil): Future[Message]
  first type mismatch at position: 7
  missing parameter: entities

expression: sendMessage(b, response.chat.id, text, parseMode = "markdown",
            disableNotification = true, replyToMessageId = response.messageId)

PS Love your library!

newForceReply not prompting reply interface and a possible solution

Hello again...
I've been trying to implement the force reply option as stated in the telegram docs: https://core.telegram.org/bots/api#sendmessage and https://core.telegram.org/bots/api#forcereply
The following example was not working:

proc askme(b: Telebot, c:Command): Future[bool] {.async.} =
    var
      username = $c.message.fromUser.get().username.get()

      
   let replyMarkup = newForceReply(selective = true)
   discard await b.sendMessage(parseInt(chat), "u drunk @$1?" % username, replyMarkup = replyMarkup)

After analyzing the code I was able to make this work by editing the following code:

In Types.nim:

  ForceReply* = ref object of KeyboardMarkup
    forceReply*: Option[bool]  ## added this
    inputFieldPlaceholder*: Option[string]

In keyboard.nim

proc newForceReply*(selective: bool, inputFieldPlaceholder = ""): ForceReply =
  new(result)
  result.kind = kForceReply
  result.forceReply = some(true) ## added this
  result.selective = some(selective)
  if inputFieldPlaceholder.len != 0:
    result.inputFieldPlaceholder = some(inputFieldPlaceholder)

the code now works for me and prompts the reply after issuing the command. I don't know if this has been an issue before, but I hope it helps :)

make the default logs optional

The default logs can be quite annoying while developing a bot, could you make it optional?

By "default logs" I mean these:

(kind: JSMN_STRING, start: 274, stop: 281, size: 0, parent: 34) kaletaa
(kind: JSMN_STRING, start: 233, stop: 240, size: 0, parent: 30) kaletaa
(kind: JSMN_STRING, start: 255, stop: 260, size: 0, parent: 32) private

Inconsistency in echo example

When a command is called, for example /hello, it gets treated twice. Once in bot.onUpdate(handler) and the second time in bot.onCommand("hello", greatingCb). How should I go about executing only a piece of code?

I'd like to execute the related code for each command by calling .onCommand and deal with all other things with .onUpdate. Now I'm not sure this is the right way of dealing with new messages so please tell me if I'm wrong.

sendMediaGroup compiler error

Seems sendMediaGroup can't accept sendMediaGroup and others.

To reproduce:

let bot = newTeleBot(API_KEY)
let doc = "file://" & getAppDir() & "/test.mid"
let media = @[
  newInputMediaDocument(doc, "file 1")
]
discard waitFor bot.sendMediaGroup($CHAT_ID, media)

Output:

~/proj/tbot/src/tbot.nim(20, 20) Error: type mismatch: got <TeleBot, string, seq[InputMediaDocument]>
but expected one of: 
proc sendMediaGroup(b: TeleBot; chatId = ""; media: seq[InputMedia];
                    disableNotification = false;
                    allowSendingWithoutReply = false; replyToMessageId = 0): Future[
    bool]
  first type mismatch at position: 3
  required type for media: seq[InputMedia]
  but expression 'media' is of type: seq[InputMediaDocument]

Error: unhandled exception: Can't obtain a value from a `none` [UnpackError]

Every Time I Tried Your Examples and Write My Own Bot, They always return an unhandled exception. Error: unhandled exception: Can't obtain a value from a none [UnpackError]

(kind: JSMN_STRING, start: 52513, stop: 52516, size: 0, parent: 5466) url (kind: JSMN_STRING, start: 52529, stop: 52545, size: 0, parent: 5468) Maksudnya Gimana /home/nayef/.choosenim/toolchains/nim-0.20.0/lib/pure/options.nim(181) get /home/nayef/.choosenim/toolchains/nim-0.20.0/lib/pure/asyncfutures.nim(353) read /home/nayef/.choosenim/toolchains/nim-0.20.0/lib/pure/asyncfutures.nim(400) :anonymous Error: unhandled exception: Can't obtain a value from a none[UnpackError]

My code: https://del.dog/codeconduct.cs

Error when compiling the example in README

utils.nim(282, 7) Error: expression 'raise
  ## creates an exception object of type ``exceptn`` and sets its ``msg`` field
  ## to `message`. Returns the new exception object.
  var e465318: ref ValueError
  new(e465318)
  e465318.msg = "Unsupported node: " & lispRepr(node[1][0])
  e465318.parent = nil
  e465318' is of type 'NimNode' and has to be discarded; start of expression here: utils.nim(234, 4)

[0.6.4] Permission handling bugs

Ex-

            let user = await getChatMember(b, $response.chat.id.int, unmuteId)
            if not(user.canSendMessages.isNone or user.canSendMessages.get):
                let perms = ChatPermissions(canSendMessages: some(true), 
                canSendMediaMessages: some(true),
                canSendOtherMessages: some(true),
                canAddWebPagePreviews: some(true))
                discard await restrictChatMember(b, $response.chat.id, unmuteId, perms)

Doesn't work
Expected behaviour: Should unrestrict the group

While

        let perms = ChatPermissions(canSendMessages : some(false))
        discard await restrictChatMember(b, $response.chat.id, response.fromUser.get.id, perms)

works fine

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.