Git Product home page Git Product logo

projectbot's Introduction

TelegramBot4s

Travis CI Build Status

Telegram Bot API for Scala

The aim of this project is to provide a 100% idiomatic Scala wrapper for the new Telegram Bot API. The entire API is supported, asynchronous by default, strongly-typed (no JSON stuff/strings) and transparently camelCased.

Using it from SBT

Cross-compiled for Scala 2.11 and 2.10

resolvers += Resolver.sonatypeRepo("snapshots")

libraryDependencies += "info.mukel" %% "telegrambot4s" % "1.0.2-SNAPSHOT"

About TOKEN safety

Please DO NOT SHARE BOT TOKENS in any form.

In order to avoid unintentional TOKEN sharing, a simple but efficient method is to store a separate file UNTRACKED, OUTSIDE THE REPO!!! e.g. "mybot.token" and spawn your bot as follows:

Then you can safely share your code and submit pull requests.

  object MyBot extends TelegramBot(Utils.tokenFromFile("./mybot.token"))
               with Polling with Commands {
               
    on("hello") { (sender, args) =>
      replyTo(sender) {
      	"My token is safe!!!"
      }
    }

  }
  
  MyBot.run()
  

Supported API:

  • getMe
  • sendMessage
  • getUpdates (polling)
  • forwardMessage
  • sendPhoto
  • sendAudio
  • sendVoice
  • sendDocument
  • sendSticker
  • sendVideo
  • sendLocation
  • sendChatAction
  • getUserProfilePhotos
  • getUpdates
  • setWebhooks
  • getFile
  • answerInlineQuery
  • Inline Mode
  • Custom keyboard markups
  • Self-signed certificates (bare)

Would be nice to:

  • Add proper logging
  • Improve error/exception handling
  • Improve the usage of self-signed certificates

Webhooks vs Polling (getUpdates)

Both polling and web hooks are supported. Polling is by far the easiest method, and can be used locally without any additional requirements.

Using web hooks requires a server (it won't work on your laptop) and a valid SSL certificate (which costs money). Self signed certificates wont work are supported now since August 29th, see the API recent changes.

The certificate requirement can be easily overcome by using the CloudFlare Universal SSL feature, which is awesome (and free). Another possible solution is hosting your bot on Google App Engine; the free quotas should be more than enough. See GenginedBot for a reference (but somehow dated) implementation.

Self-signed certificates

Self-signed certificates are already supported, but not friendly at all, the user still has to worry about creating the certificates..., the goal is to add the functionality directly into the Webhooks trait, completely transparent to the user. The desired flow would be something like: generate certificate, set webhook and run.

Bonus (or how to turn a spare phone into a Telegram Bot)

Beside the usual ways, I've managed to run FlunkeyBot successfully on a Raspberry Pi 2, and most notably on an old Android (4.1.2) phone with a broken screen.

About blocking

All API calls are aysnc thanks to Andrey Romanov, still all updates are processed sequentially which makes sense since the order of incoming messages should (usually) match the order of responses; in case the order doesn't matter, updates can be handled asynchonously, see Async Bot below.

Contributions

Contributions are highly appreciated, documentation improvements/corrections, better ways to do things. Writing a bot using this library is also a way to contribute, I'll add a link to your bot here in README anytime. Thanks to Andrey Romanov and ex0ns for their contributions.

Usage

  val helloBot = new TelegramBot(TOKEN) with Polling with Commands
  
  helloBot.on("hello") { (sender, args) =>
    replyTo(sender) {
      "Hello World!"
    }
  }
  
  helloBot.run()
  

Or

  object CoolBot extends TelegramBot(TOKEN) with Polling with Commands {
  
    import info.mukel.telegram.bots.OptionPimps._

    // Let Me Google That For You :)    
    on("lmgtfy") { (sender, args) =>
      replyTo(sender, disableWebPagePreview = true) {
        "http://lmgtfy.com/?q=" + URLEncoder.encode(args mkString " ", "UTF-8")
      }
    }

    on("echo") { (sender, args) =>
      replyTo(sender) {
      	args mkString " "
      }
    }
  }
  
  CoolBot.run()
  

Async bot

  object AsyncBot extends TelegramBot(TOKEN) with Polling with Commands {
  
    import info.mukel.telegram.bots.OptionPimps._
    
    on("expensive_computation") { (sender, args) => Future {
      replyTo(sender) {
      	// Expensive computation here
      	Thread.sleep(10000)
      	"42"
      }
    }}
    
    // Send a photo aysnchronously
    on("bender") { (sender, _) => Future {
      sendPhoto(sender, InputFile("./bender_photo.jpg"),
                caption = "Bender the great!!!")
    }}
  }
  
  AsyncBot.run()
  

Bot using web hooks (maybe broken)

  object WebhookedBot extends TelegramBot(TOKEN) with Webhooks with Commands {

    // The URL must contain the token to validate the request
    override val webHookUrl = "https://webhooks.yoursite.com/" + token
    
    on("hello") { (sender, args) =>
      replyTo(sender) {
        "Hello World!"
      }
    }

  }
  
  WebhookedBot.run()
  

projectbot's People

Contributors

ironjanowar avatar rockneurotiko avatar

Watchers

Alvaro Vila avatar James Cloos avatar  avatar Álvaro avatar Ashida avatar foldr avatar Paloma Pedregal avatar  avatar Samuel Requena avatar Diego Martínez avatar Rubén Aguado Cosano avatar Andrés Sánchez avatar Javier Antonio Román López avatar Carlos Sanchez avatar Víctor Villar avatar

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.