Skip to content

Commit c01becd

Browse files
committed
new callback process
1 parent 6d7c78d commit c01becd

File tree

13 files changed

+149
-178
lines changed

13 files changed

+149
-178
lines changed

README.md

Lines changed: 22 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,55 +12,43 @@ Usage
1212

1313
## echo bot
1414
```nim
15-
import telebot, asyncdispatch, options
15+
import telebot, asyncdispatch, logging, options
1616
1717
const API_KEY = slurp("secret.key")
1818
19-
proc handleUpdate(bot: TeleBot): UpdateCallback =
20-
proc cb(e: Update) {.async.} =
21-
var response = e.message.get
22-
if response.text.isSome:
23-
let
24-
text = response.text.get
25-
var message = newMessage(response.chat.id, text)
26-
message.disableNotification = true
27-
message.replyToMessageId = response.messageId
28-
message.parseMode = "markdown"
29-
discard bot.send(message)
30-
result = cb
31-
32-
let
33-
bot = newTeleBot(API_KEY)
34-
handler = handleUpdate(bot)
35-
bot.onUpdate(handler)
19+
proc updateHandler(b: Telebot, u: Update) {.async.} =
20+
var response = u.message.get
21+
if response.text.isSome:
22+
let
23+
text = response.text.get
24+
var message = newMessage(response.chat.id, text)
25+
message.disableNotification = true
26+
message.replyToMessageId = response.messageId
27+
message.parseMode = "markdown"
28+
discard await b.send(message)
29+
30+
let bot = newTeleBot(API_KEY)
31+
bot.onUpdate(updateHandler)
3632
bot.poll(300)
37-
3833
```
3934

4035
## send local photo
4136
```nim
4237
import telebot, asyncdispatch, options, logging
4338
44-
var L = newConsoleLogger(fmtStr="$levelname, [$time] ")
45-
addHandler(L)
46-
4739
const API_KEY = slurp("secret.key")
4840
49-
proc handleUpdate(bot: TeleBot): UpdateCallback =
50-
proc cb(e: Update) {.async.} =
51-
var response = e.message.get
52-
if response.text.isSome:
53-
let
54-
text = response.text.get
55-
var message = newPhoto(response.chat.id, "file:///path/to/photo.jpg")
56-
discard await bot.send(message)
57-
result = cb
41+
proc updateHandler(bot: TeleBot, update: Update): UpdateCallback =
42+
var response = update.message.get
43+
if response.text.isSome:
44+
let
45+
text = response.text.get
46+
var message = newPhoto(response.chat.id, "file:///path/to/photo.jpg")
47+
discard await bot.send(message)
5848
5949
let
6050
bot = newTeleBot(API_KEY)
61-
handler = handleUpdate(bot)
62-
63-
bot.onUpdate(handler)
51+
bot.onUpdate(updateHandler)
6452
bot.poll(300)
6553
```
6654
For more information please refer to official [Telegram Bot API](https://core.telegram.org/bots/api) page

examples/echo_bot.nim

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,28 @@ addHandler(L)
55

66
const API_KEY = slurp("secret.key")
77

8-
proc handleUpdate(bot: TeleBot): UpdateCallback =
9-
proc cb(e: Update) {.async.} =
10-
var response = e.message.get
11-
if response.text.isSome:
12-
let
13-
text = response.text.get
14-
var message = newMessage(response.chat.id, text)
15-
message.disableNotification = true
16-
message.replyToMessageId = response.messageId
17-
message.parseMode = "markdown"
18-
discard await bot.send(message)
19-
result = cb
20-
21-
proc greatingHandler(bot: Telebot): CommandCallback =
22-
proc cb(e: Command) {.async.} =
23-
var message = newMessage(e.message.chat.id, "hello " & e.message.fromUser.get().firstName)
8+
proc updateHandler(b: Telebot, u: Update) {.async.} =
9+
var response = u.message.get
10+
if response.text.isSome:
11+
let
12+
text = response.text.get
13+
var message = newMessage(response.chat.id, text)
2414
message.disableNotification = true
25-
message.replyToMessageId = e.message.messageId
15+
message.replyToMessageId = response.messageId
2616
message.parseMode = "markdown"
27-
discard bot.send(message)
17+
discard await b.send(message)
18+
2819

29-
result = cb
20+
proc greatingHandler(b: Telebot, c: Command) {.async.} =
21+
var message = newMessage(c.message.chat.id, "hello " & c.message.fromUser.get().firstName)
22+
message.disableNotification = true
23+
message.replyToMessageId = c.message.messageId
24+
message.parseMode = "markdown"
25+
discard b.send(message)
3026

3127
when isMainModule:
32-
let
33-
bot = newTeleBot(API_KEY)
34-
handler = handleUpdate(bot)
35-
greatingCb = greatingHandler(bot)
28+
let bot = newTeleBot(API_KEY)
3629

37-
bot.onUpdate(handler)
38-
bot.onCommand("hello", greatingCb)
30+
bot.onUpdate(updateHandler)
31+
bot.onCommand("hello", greatingHandler)
3932
bot.poll(300)
Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,35 @@
11
# This Bot receives any Document file, responds on chat with file metadata and file contents.
22
import telebot, asyncdispatch, options, strformat, httpclient, json
33

4-
const API_KEY = "" # Add your API Key here.
4+
const API_KEY = slurp("secret.key")
55

66

7-
proc handleUpdate(bot: TeleBot): UpdateCallback =
7+
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
88
let
99
url_getfile = fmt"https://api.telegram.org/bot{API_KEY}/getFile?file_id="
1010
api_file = fmt"https://api.telegram.org/file/bot{API_KEY}/"
1111

12-
proc cb(e: Update) {.async.} =
13-
var response = e.message.get
14-
if response.document.isSome:
15-
let
16-
document = response.document.get
17-
file_name = document.file_name.get
18-
mime_type = document.mime_type.get
19-
file_id = document.file_id
20-
file_size = document.file_size.get
21-
responz = await newAsyncHttpClient().get(url_getfile & file_id) # file_id > file_path
22-
responz_body = await responz.body
23-
file_path = parseJson(responz_body)["result"]["file_path"].getStr()
24-
responx = await newAsyncHttpClient().get(api_file & file_path) # file_path > file
25-
file_content = await responx.body
26-
msg0_text = fmt"file_name: {file_name}, mime_type: {mime_type}, file_id: {file_id}, file_size: {file_size}, file_path: {file_path}"
27-
var
28-
message0 = newMessage(response.chat.id, msg0_text) # metadata
29-
message1 = newMessage(response.chat.id, file_content) # file contents
30-
discard await bot.send(message0)
31-
discard await bot.send(message1)
32-
result = cb
12+
var response = e.message.get
13+
if response.document.isSome:
14+
let
15+
document = response.document.get
16+
file_name = document.file_name.get
17+
mime_type = document.mime_type.get
18+
file_id = document.file_id
19+
file_size = document.file_size.get
20+
responz = await newAsyncHttpClient().get(url_getfile & file_id) # file_id > file_path
21+
responz_body = await responz.body
22+
file_path = parseJson(responz_body)["result"]["file_path"].getStr()
23+
responx = await newAsyncHttpClient().get(api_file & file_path) # file_path > file
24+
file_content = await responx.body
25+
msg0_text = fmt"file_name: {file_name}, mime_type: {mime_type}, file_id: {file_id}, file_size: {file_size}, file_path: {file_path}"
26+
var
27+
message0 = newMessage(response.chat.id, msg0_text) # metadata
28+
message1 = newMessage(response.chat.id, file_content) # file contents
29+
discard await bot.send(message0)
30+
discard await bot.send(message1)
3331

34-
let
35-
bot = newTeleBot(API_KEY)
36-
handler = handleUpdate(bot)
37-
bot.onUpdate(handler)
32+
let bot = newTeleBot(API_KEY)
33+
34+
bot.onUpdate(updateHandler)
3835
bot.poll(666)
Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
# This Bot Sends itself as Document file, responds on chat with source file to download.
22
import telebot, asyncdispatch, options, os
33

4-
const API_KEY = "" # Add your API Key here.
4+
const API_KEY = slurp("secret.key")
55

66

7-
proc handleUpdate(bot: TeleBot): UpdateCallback =
7+
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
88
let this_file = "file://" & getCurrentDir() & "/file_send_bot.nim"
9-
proc cb(e: Update) {.async.} =
10-
var document = newDocument(e.message.get.chat.id, this_file)
11-
document.caption = this_file
12-
discard await bot.send(document)
13-
result = cb
9+
10+
var document = newDocument(e.message.get.chat.id, this_file)
11+
document.caption = this_file
12+
discard await bot.send(document)
1413

1514
let bot = newTeleBot(API_KEY)
16-
bot.onUpdate(handleUpdate(bot))
15+
bot.onUpdate(updateHandler)
1716
bot.poll(666)

examples/geo_location_bot/geo_bot.nim

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import telebot, asyncdispatch, options
22

3-
const API_KEY = "" # Add your API Key here.
3+
const API_KEY = slurp("secret.key")
44

5-
proc geoHandler(bot: TeleBot): CommandCallback =
6-
proc cb(e: Command) {.async.} =
7-
let message = newLocation(e.message.chat.id, longitude=42.0, latitude=42.0)
8-
discard await bot.send(message)
9-
result = cb
5+
proc geoHandler(bot: TeleBot, e: Command) {.async.} =
6+
let message = newLocation(e.message.chat.id, longitude=42.0, latitude=42.0)
7+
discard await bot.send(message)
108

119
let bot = newTeleBot(API_KEY)
12-
bot.onCommand("geo", geoHandler(bot)) # Use /geo on Telegram chat to trigger.
10+
bot.onCommand("geo", geoHandler) # Use /geo on Telegram chat to trigger.
1311
bot.poll(666)

examples/image_bot.nim

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ addHandler(L)
55
from cgi import encodeUrl
66
const API_KEY = slurp("secret.key")
77

8-
proc fetchResults(query: string): Future[seq[InlineQueryResultPhoto]] {.async.} =
9-
result = @[]
10-
let url = "https://api.reddit.com/r/unixporn/search?limit=6&type=link&q=" & encodeUrl(query)
8+
proc queryHandler(b: TeleBot, q: InlineQuery) {.async.} =
9+
let url = "https://api.reddit.com/r/unixporn/search?limit=6&type=link&q=" & encodeUrl(q.query)
1110
var
1211
client = newAsyncHttpClient()
1312
response = await client.get(url)
13+
photos: seq[InlineQueryResultPhoto] = @[]
1414
if response.code == Http200:
1515
var data = parseJson(await response.body)
1616
for child in data["data"]["children"].items:
@@ -22,20 +22,12 @@ proc fetchResults(query: string): Future[seq[InlineQueryResultPhoto]] {.async.}
2222
photo.photoUrl = child["data"]["url"].str
2323
photo.thumbUrl = child["data"]["thumbnail"].str
2424
photo.title = some($child["data"]["title"])
25-
result.add(photo)
2625

27-
var updates: seq[Update]
28-
proc main() {.async.} =
29-
let bot = newTeleBot(API_KEY, "nim_telebot")
26+
photos.add(photo)
3027

31-
while true:
32-
updates = await bot.getUpdates(timeout=300)
33-
for update in updates:
34-
if update.inlineQuery.isNone:
35-
continue
36-
var
37-
query = update.inlineQuery.get
38-
results = await fetchResults(query.query)
39-
discard await bot.answerInlineQuery(query.id, results)
40-
asyncCheck main()
41-
runForever()
28+
discard await b.answerInlineQuery(q.id, photos)
29+
30+
when isMainModule:
31+
let bot = newTeleBot(API_KEY)
32+
bot.onInlineQuery(queryHandler)
33+
bot.poll(300)

examples/inline_keyboard.nim

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,27 @@ const API_KEY = slurp("secret.key")
88
var updates: seq[Update]
99

1010

11-
proc handleUpdate(bot: TeleBot): UpdateCallback =
12-
proc cb(e: Update) {.async.} =
13-
var response = e.message.get
14-
if response.text.isSome:
15-
let
16-
text = response.text.get
17-
var
18-
message = newMessage(response.chat.id, text)
19-
google = initInlineKeyboardButton("Google")
20-
bing = initInlineKeyboardButton("Bing")
21-
ddg = initInlineKeyboardButton("DuckDuckGo")
22-
searx = initInlineKeyboardButton("searx.me")
23-
24-
google.url = some("https://www.google.com/search?q=" & text)
25-
bing.url = some("https://www.bing.com/search?q=" & text)
26-
ddg.url = some("https://duckduckgo.com/?q=" & text)
27-
searx.url = some("https://searx.me/?q=" & text)
28-
29-
message.replyMarkup = newInlineKeyboardMarkup(@[google, bing], @[ddg, searx])
30-
discard await bot.send(message)
31-
result = cb
11+
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
12+
var response = e.message.get
13+
if response.text.isSome:
14+
let
15+
text = response.text.get
16+
var
17+
message = newMessage(response.chat.id, text)
18+
google = initInlineKeyboardButton("Google")
19+
bing = initInlineKeyboardButton("Bing")
20+
ddg = initInlineKeyboardButton("DuckDuckGo")
21+
searx = initInlineKeyboardButton("searx.me")
22+
23+
google.url = some("https://www.google.com/search?q=" & text)
24+
bing.url = some("https://www.bing.com/search?q=" & text)
25+
ddg.url = some("https://duckduckgo.com/?q=" & text)
26+
searx.url = some("https://searx.me/?q=" & text)
27+
28+
message.replyMarkup = newInlineKeyboardMarkup(@[google, bing], @[ddg, searx])
29+
discard await bot.send(message)
3230

3331
when isMainModule:
34-
let
35-
bot = newTeleBot(API_KEY)
36-
handler = handleUpdate(bot)
37-
38-
bot.onUpdate(handler)
32+
let bot = newTeleBot(API_KEY)
33+
bot.onUpdate(updateHandler)
3934
bot.poll(300)
Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
import telebot, asyncdispatch, options, logging, os
22

33

4-
const API_KEY = "" # Add your API Key here.
4+
const API_KEY = slurp("secret.key")
55

66

77
addHandler(newConsoleLogger(fmtStr="$levelname, [$time] "))
88

9-
proc handleUpdate(bot: TeleBot): UpdateCallback =
10-
proc cb(e: Update) {.async.} =
11-
let message = newPhoto(e.message.get.chat.id, "file://" & getCurrentDir() & "/sample.jpg")
12-
discard await bot.send(message)
13-
result = cb
9+
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
10+
let message = newPhoto(e.message.get.chat.id, "file://" & getCurrentDir() & "/sample.jpg")
11+
discard await bot.send(message)
1412

15-
let
16-
bot = newTeleBot(API_KEY)
17-
handler = handleUpdate(bot)
13+
let bot = newTeleBot(API_KEY)
1814

19-
bot.onUpdate(handler)
15+
bot.onUpdate(updateHandler)
2016
bot.poll(500)

telebot.nim

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import asyncevents except off
1+
import tables
22

33
import telebot/[types, keyboard, webhook, inputmedia]
44
export types, webhook, keyboard, inputmedia
@@ -8,8 +8,9 @@ proc newTeleBot*(token: string): TeleBot =
88
new(result)
99
result.token = token
1010
result.lastUpdateId = 0
11-
result.updateEmitter = initAsyncEventEmitter[Update, string]()
12-
result.commandEmitter = initAsyncEventEmitter[Command, string]()
11+
result.updateCallbacks = @[]
12+
result.commandCallbacks = newTable[string, seq[CommandCallback]]()
13+
result.inlineQueryCallbacks = @[]
1314

1415
include telebot/api
1516
include telebot/events

telebot.nimble

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
version = "0.4.0"
1+
version = "0.4.1"
22
author = "Huy Doan"
33
description = "Async Telegram Bot API Client"
44
license = "MIT"
55
skipDirs = @["examples"]
66

77
requires "nim >= 0.17.0"
8-
requires "asyncevents >= 0.3.0"

0 commit comments

Comments
 (0)