Skip to content

Commit

Permalink
new callback process
Browse files Browse the repository at this point in the history
  • Loading branch information
ba0f3 committed Aug 4, 2018
1 parent 6d7c78d commit c01becd
Show file tree
Hide file tree
Showing 13 changed files with 149 additions and 178 deletions.
56 changes: 22 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,55 +12,43 @@ Usage

## echo bot
```nim
import telebot, asyncdispatch, options
import telebot, asyncdispatch, logging, options
const API_KEY = slurp("secret.key")
proc handleUpdate(bot: TeleBot): UpdateCallback =
proc cb(e: Update) {.async.} =
var response = e.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 bot.send(message)
result = cb
let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)
bot.onUpdate(handler)
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(300)
```

## send local photo
```nim
import telebot, asyncdispatch, options, logging
var L = newConsoleLogger(fmtStr="$levelname, [$time] ")
addHandler(L)
const API_KEY = slurp("secret.key")
proc handleUpdate(bot: TeleBot): UpdateCallback =
proc cb(e: Update) {.async.} =
var response = e.message.get
if response.text.isSome:
let
text = response.text.get
var message = newPhoto(response.chat.id, "file:///path/to/photo.jpg")
discard await bot.send(message)
result = cb
proc updateHandler(bot: TeleBot, update: Update): UpdateCallback =
var response = update.message.get
if response.text.isSome:
let
text = response.text.get
var message = newPhoto(response.chat.id, "file:///path/to/photo.jpg")
discard await bot.send(message)
let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)
bot.onUpdate(handler)
bot.onUpdate(updateHandler)
bot.poll(300)
```
For more information please refer to official [Telegram Bot API](https://core.telegram.org/bots/api) page
43 changes: 18 additions & 25 deletions examples/echo_bot.nim
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,28 @@ addHandler(L)

const API_KEY = slurp("secret.key")

proc handleUpdate(bot: TeleBot): UpdateCallback =
proc cb(e: Update) {.async.} =
var response = e.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 bot.send(message)
result = cb

proc greatingHandler(bot: Telebot): CommandCallback =
proc cb(e: Command) {.async.} =
var message = newMessage(e.message.chat.id, "hello " & e.message.fromUser.get().firstName)
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 = e.message.messageId
message.replyToMessageId = response.messageId
message.parseMode = "markdown"
discard bot.send(message)
discard await b.send(message)


result = cb
proc greatingHandler(b: Telebot, c: Command) {.async.} =
var message = newMessage(c.message.chat.id, "hello " & c.message.fromUser.get().firstName)
message.disableNotification = true
message.replyToMessageId = c.message.messageId
message.parseMode = "markdown"
discard b.send(message)

when isMainModule:
let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)
greatingCb = greatingHandler(bot)
let bot = newTeleBot(API_KEY)

bot.onUpdate(handler)
bot.onCommand("hello", greatingCb)
bot.onUpdate(updateHandler)
bot.onCommand("hello", greatingHandler)
bot.poll(300)
51 changes: 24 additions & 27 deletions examples/file_receive_bot/file_receive_bot.nim
Original file line number Diff line number Diff line change
@@ -1,38 +1,35 @@
# This Bot receives any Document file, responds on chat with file metadata and file contents.
import telebot, asyncdispatch, options, strformat, httpclient, json

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


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

proc cb(e: Update) {.async.} =
var response = e.message.get
if response.document.isSome:
let
document = response.document.get
file_name = document.file_name.get
mime_type = document.mime_type.get
file_id = document.file_id
file_size = document.file_size.get
responz = await newAsyncHttpClient().get(url_getfile & file_id) # file_id > file_path
responz_body = await responz.body
file_path = parseJson(responz_body)["result"]["file_path"].getStr()
responx = await newAsyncHttpClient().get(api_file & file_path) # file_path > file
file_content = await responx.body
msg0_text = fmt"file_name: {file_name}, mime_type: {mime_type}, file_id: {file_id}, file_size: {file_size}, file_path: {file_path}"
var
message0 = newMessage(response.chat.id, msg0_text) # metadata
message1 = newMessage(response.chat.id, file_content) # file contents
discard await bot.send(message0)
discard await bot.send(message1)
result = cb
var response = e.message.get
if response.document.isSome:
let
document = response.document.get
file_name = document.file_name.get
mime_type = document.mime_type.get
file_id = document.file_id
file_size = document.file_size.get
responz = await newAsyncHttpClient().get(url_getfile & file_id) # file_id > file_path
responz_body = await responz.body
file_path = parseJson(responz_body)["result"]["file_path"].getStr()
responx = await newAsyncHttpClient().get(api_file & file_path) # file_path > file
file_content = await responx.body
msg0_text = fmt"file_name: {file_name}, mime_type: {mime_type}, file_id: {file_id}, file_size: {file_size}, file_path: {file_path}"
var
message0 = newMessage(response.chat.id, msg0_text) # metadata
message1 = newMessage(response.chat.id, file_content) # file contents
discard await bot.send(message0)
discard await bot.send(message1)

let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)
bot.onUpdate(handler)
let bot = newTeleBot(API_KEY)

bot.onUpdate(updateHandler)
bot.poll(666)
15 changes: 7 additions & 8 deletions examples/file_send_bot/file_send_bot.nim
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
# This Bot Sends itself as Document file, responds on chat with source file to download.
import telebot, asyncdispatch, options, os

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


proc handleUpdate(bot: TeleBot): UpdateCallback =
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
let this_file = "file://" & getCurrentDir() & "/file_send_bot.nim"
proc cb(e: Update) {.async.} =
var document = newDocument(e.message.get.chat.id, this_file)
document.caption = this_file
discard await bot.send(document)
result = cb

var document = newDocument(e.message.get.chat.id, this_file)
document.caption = this_file
discard await bot.send(document)

let bot = newTeleBot(API_KEY)
bot.onUpdate(handleUpdate(bot))
bot.onUpdate(updateHandler)
bot.poll(666)
12 changes: 5 additions & 7 deletions examples/geo_location_bot/geo_bot.nim
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import telebot, asyncdispatch, options

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

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

let bot = newTeleBot(API_KEY)
bot.onCommand("geo", geoHandler(bot)) # Use /geo on Telegram chat to trigger.
bot.onCommand("geo", geoHandler) # Use /geo on Telegram chat to trigger.
bot.poll(666)
28 changes: 10 additions & 18 deletions examples/image_bot.nim
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ addHandler(L)
from cgi import encodeUrl
const API_KEY = slurp("secret.key")

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

var updates: seq[Update]
proc main() {.async.} =
let bot = newTeleBot(API_KEY, "nim_telebot")
photos.add(photo)

while true:
updates = await bot.getUpdates(timeout=300)
for update in updates:
if update.inlineQuery.isNone:
continue
var
query = update.inlineQuery.get
results = await fetchResults(query.query)
discard await bot.answerInlineQuery(query.id, results)
asyncCheck main()
runForever()
discard await b.answerInlineQuery(q.id, photos)

when isMainModule:
let bot = newTeleBot(API_KEY)
bot.onInlineQuery(queryHandler)
bot.poll(300)
47 changes: 21 additions & 26 deletions examples/inline_keyboard.nim
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,27 @@ const API_KEY = slurp("secret.key")
var updates: seq[Update]


proc handleUpdate(bot: TeleBot): UpdateCallback =
proc cb(e: Update) {.async.} =
var response = e.message.get
if response.text.isSome:
let
text = response.text.get
var
message = newMessage(response.chat.id, text)
google = initInlineKeyboardButton("Google")
bing = initInlineKeyboardButton("Bing")
ddg = initInlineKeyboardButton("DuckDuckGo")
searx = initInlineKeyboardButton("searx.me")

google.url = some("https://www.google.com/search?q=" & text)
bing.url = some("https://www.bing.com/search?q=" & text)
ddg.url = some("https://duckduckgo.com/?q=" & text)
searx.url = some("https://searx.me/?q=" & text)

message.replyMarkup = newInlineKeyboardMarkup(@[google, bing], @[ddg, searx])
discard await bot.send(message)
result = cb
proc updateHandler(bot: TeleBot, e: Update) {.async.} =
var response = e.message.get
if response.text.isSome:
let
text = response.text.get
var
message = newMessage(response.chat.id, text)
google = initInlineKeyboardButton("Google")
bing = initInlineKeyboardButton("Bing")
ddg = initInlineKeyboardButton("DuckDuckGo")
searx = initInlineKeyboardButton("searx.me")

google.url = some("https://www.google.com/search?q=" & text)
bing.url = some("https://www.bing.com/search?q=" & text)
ddg.url = some("https://duckduckgo.com/?q=" & text)
searx.url = some("https://searx.me/?q=" & text)

message.replyMarkup = newInlineKeyboardMarkup(@[google, bing], @[ddg, searx])
discard await bot.send(message)

when isMainModule:
let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)

bot.onUpdate(handler)
let bot = newTeleBot(API_KEY)
bot.onUpdate(updateHandler)
bot.poll(300)
16 changes: 6 additions & 10 deletions examples/photo_send_bot/photo_send_bot.nim
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import telebot, asyncdispatch, options, logging, os


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


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

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

let
bot = newTeleBot(API_KEY)
handler = handleUpdate(bot)
let bot = newTeleBot(API_KEY)

bot.onUpdate(handler)
bot.onUpdate(updateHandler)
bot.poll(500)
7 changes: 4 additions & 3 deletions telebot.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import asyncevents except off
import tables

import telebot/[types, keyboard, webhook, inputmedia]
export types, webhook, keyboard, inputmedia
Expand All @@ -8,8 +8,9 @@ proc newTeleBot*(token: string): TeleBot =
new(result)
result.token = token
result.lastUpdateId = 0
result.updateEmitter = initAsyncEventEmitter[Update, string]()
result.commandEmitter = initAsyncEventEmitter[Command, string]()
result.updateCallbacks = @[]
result.commandCallbacks = newTable[string, seq[CommandCallback]]()
result.inlineQueryCallbacks = @[]

include telebot/api
include telebot/events
3 changes: 1 addition & 2 deletions telebot.nimble
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
version = "0.4.0"
version = "0.4.1"
author = "Huy Doan"
description = "Async Telegram Bot API Client"
license = "MIT"
skipDirs = @["examples"]

requires "nim >= 0.17.0"
requires "asyncevents >= 0.3.0"
Loading

0 comments on commit c01becd

Please sign in to comment.