Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
zedeus committed May 24, 2019
0 parents commit a8c3bb2
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
token
nimblebot
18 changes: 18 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Copyright 2019 Zed

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# NimbleBot

NimbleBot is a simple Telegram bot for looking up Nimble packages.

To run an instance, create a new bot with @BotFather, then save your token in a
file called `token`. This file is read at compile time from the project folder,
not the src folder.
1 change: 1 addition & 0 deletions config.nims
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
switch("d", "ssl")
13 changes: 13 additions & 0 deletions nimblebot.nimble
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Package

version = "0.1.0"
author = "zedeus"
description = "Nimble Telegram bot"
license = "MIT"
srcDir = "src"
bin = @["nimblebot"]


# Dependencies

requires "nim >= 0.19.4", "telebot"
45 changes: 45 additions & 0 deletions src/data.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import sequtils, algorithm, httpclient, asyncdispatch, times
import strutils except editdistance
import std/editdistance
import sam

type
Package* = object
name*: string
tags*: seq[string]
web*: string
description*: string

const
url = "https://github.com/nim-lang/packages/raw/master/packages.json"
path = "/tmp/packages.json"

var
lastFetched = now()
interval = initDuration(hours=6)
packageList*: seq[Package]

proc updateList*() {.async.} =
if now() - lastFetched < interval and packageList.len > 0:
return

let client = newAsyncHttpClient()
await client.downloadFile(url, path)
packageList.loads(readFile(path))

lastFetched = now()

proc searchTags(p: Package; search: string): bool =
for t in p.tags:
if search in t.toLower():
return true

proc calcRank(p: Package; search: string): int =
if search == p.name: result -= 20
if search in p.name: result -= 10
if search in p.description.toLower(): result -= 5
if searchTags(p, search): result -= 10
result += editDistance(search, p.name.toLower())

proc getMatches*(search: string): seq[Package] =
packageList.sortedByIt(calcRank(it, search.toLower().strip()))
87 changes: 87 additions & 0 deletions src/nimblebot.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import os, options, asyncdispatch, net, times, strformat, sequtils, algorithm
import strutils except editdistance
import std/editdistance

import telebot

import data

const token = slurp("../token").strip()

var me: User

template sendText(text: string; replyId=0; parse="markdown") =
var msg = newMessage(u.message.chat.id, text)
asyncCheck b.send(msg)

proc start(b: Telebot, u: Command) {.async.} =
sendText("This bot is inline-mode only. /help for instructions.")

proc help(b: Telebot, u: Command) {.async.} =
sendText("Type @" & me.username.get & " to search for Nimble packages.")

proc inlineHandler(b: Telebot, u: InlineQuery) {.async.} =
if u.query.len < 2: return

await updateList()

let matches = getMatches(u.query)
var results: seq[InlineQueryResultArticle]

for p in matches:
if results.len == 15: break

var res: InlineQueryResultArticle
res.kind = "article"
res.title = p.name
res.id = $(results.len + 1)

var content = &"<b>{p.name}</b>"

if p.description.len > 0:
res.description = some(p.description)
content &= "\n\n" & p.description

content &= "\n\n" & p.web

var textContent = InputTextMessageContent(content)
textContent.parseMode = some("html")
res.inputMessageContent = some(textContent)

results.add(res)

asyncCheck b.answerInlineQuery(u.id, results, cacheTime=10)

proc startup(b: Telebot) =
try:
me = waitFor b.getMe()
echo "ID: ", me.id
echo "First Name: ", me.firstName
echo "User Name: ", me.username.get()
except OSError:
let e = getCurrentException()
echo e.name, " ", e.msg
quit()

proc main =
let bot = newTeleBot(token)
startup(bot)

bot.onInlineQuery(inlineHandler)
bot.onCommand("start", start)
bot.onCommand("help", help)

waitFor updateList()

while true:
try:
bot.poll(clean=true)
except IOError, OSError, SslError:
let e = getCurrentException()
echo e.name, " ", e.msg

if "Bad Gateway" in e.msg or "Time" in e.msg:
sleep(2)
discard

main()

0 comments on commit a8c3bb2

Please sign in to comment.