All Projects → bot4s → Telegram

bot4s / Telegram

Licence: apache-2.0
Telegram Bot API Wrapper for Scala

Programming Languages

scala
5932 projects

Projects that are alternatives of or similar to Telegram

Java Telegram Bot Api
Telegram Bot API for Java
Stars: ✭ 819 (+164.19%)
Mutual labels:  telegram-bot-api, telegram-api, telegram-bot, telegram
Botserver
http://telegram.org Bot API Webhooks Framework, for Rubyists
Stars: ✭ 125 (-59.68%)
Mutual labels:  telegram-bot-api, telegram-bot, webhook, telegram
Python Telegram
Python client for the Telegram's tdlib
Stars: ✭ 246 (-20.65%)
Mutual labels:  telegram-bot-api, telegram-api, telegram-bot, telegram
webhook-aiogram-heroku
A sample telegram bot made with aiogram, that fetches updates using the web-hook connection. Can be easily deployed to Heroku.
Stars: ✭ 36 (-88.39%)
Mutual labels:  telegram, telegram-bot, webhook, telegram-bot-api
Informer
A Telegram Mass Surveillance Bot in Python
Stars: ✭ 745 (+140.32%)
Mutual labels:  telegram-bot-api, telegram-api, telegram-bot, telegram
Mypackbot
🤖 Your own unlimited pack of Telegram-stickers
Stars: ✭ 18 (-94.19%)
Mutual labels:  telegram-bot-api, telegram-api, telegram-bot, telegram
Java Telegram Bot Tutorial
Java Telegram Bot Tutorial. Feel free to submit issue if you found a mistake.
Stars: ✭ 165 (-46.77%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
Rastreiobot
Telegram Bot @RastreioBot
Stars: ✭ 196 (-36.77%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
Telegrammer
Telegram Bot - written with Swift 5.2 / NIO, supports Linux, macOS
Stars: ✭ 248 (-20%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
grouphelperbot
A Telegram Bot made to help group admins, with Italian/English support.
Stars: ✭ 26 (-91.61%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
Bybit-Auto-Trading-Bot-Ordes-placed-via-TradingView-Webhook
Python based Trading Bot that uses TradingView.com webhook JSON alerts to place orders(buy/sell/close/manage positions/TP/SL/TS etc.) on Bybit.com. Hire me directly here https://www.freelancer.com/u/Beannsofts for any assistance
Stars: ✭ 235 (-24.19%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
telegram
📚 Golang bindings for Telegram API
Stars: ✭ 15 (-95.16%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
Telegram Bot Sdk
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.
Stars: ✭ 2,212 (+613.55%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
Teledart
A Dart library interfacing with the latest Telegram Bot API.
Stars: ✭ 142 (-54.19%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
Telegram.bot
.NET Client for Telegram Bot API
Stars: ✭ 1,964 (+533.55%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram
tdlight-telegram-bot-api
The TDLight Telegram Bot API is an actively enhanced fork of the original Bot API, featuring experimental user support, proxies, unlimited files size, and more.
Stars: ✭ 71 (-77.1%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
LilSholex
A project containing web apps and Telegram API bots.
Stars: ✭ 32 (-89.68%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
echotron
An elegant and concurrent library for Telegram bots in Go.
Stars: ✭ 95 (-69.35%)
Mutual labels:  telegram-bot, telegram-api, telegram-bot-api
checkmk-telegram-notify
Get alerted by Check_MK via Telegram bash script
Stars: ✭ 28 (-90.97%)
Mutual labels:  telegram, telegram-bot, telegram-bot-api
Zanzara
Asynchronous PHP Telegram Bot Framework built on top of ReactPHP
Stars: ✭ 107 (-65.48%)
Mutual labels:  telegram-bot-api, telegram-bot, telegram

Idiomatic Scala wrapper for the Telegram Bot API

Buy Me A Coffee donate button

bot4s.telegram

Simple, extensible, strongly-typed wrapper for the Telegram Bot API.

Table of contents

As SBT/mill dependency

Add to your build.sbt file:

// Core with minimal dependencies, enough to spawn your first bot.
libraryDependencies += "com.bot4s" %% "telegram-core" % "4.4.0-RC2"

// Extra goodies: Webhooks, support for games, bindings for actors.
libraryDependencies += "com.bot4s" %% "telegram-akka" % "4.4.0-RC2"

For mill add to your build.sc project deps:

ivy"com.bot4s::telegram-core:4.4.0-RC2", // core
ivy"com.bot4s::telegram-akka:4.4.0-RC2"  // extra goodies

Leaking bot tokens

Don't ever expose your bot's token.

Hopefully GitGuardian got you covered and will warn you about exposed API keys.

Webhooks vs. Polling

Both methods are supported. (Long) Polling is bundled in the core artifact and it's by far the easiest method.

Webhook support comes in the extra artifact based on akka-http; requires a server, it won't work on your laptop. For a comprehensive reference check Marvin's Patent Pending Guide to All Things Webhook.

Payments

Payments are supported since version 3.0; refer to official payments documentation for details. I'll support developers willing to integrate and/or improve the payments API; please report issues here.

Games

The Akka extensions include support for games in two flavors; self-hosted (served by the bot itself), and external, hosted on e.g. GitHub Pages. Check both the self-hosted and GitHub-hosted versions of the popular 2048 game.

Deployment

bot4s.telegram runs on Raspberry Pi, Heroku, Google App Engine and most notably on an old Android (4.1.2) phone with a broken screen via the JDK for ARM. Bots also runs flawlessly on top of my master thesis: "A meta-circular Java bytecode interpreter for the GraalVM".

Distribution/deployment is outside the scope of the library, but all platforms where Java is supported should be compatible. You may find sbt-assembly and sbt-docker very handy.

Scala.js is also supported, bots can run on the browser via the SttpClient. NodeJs is not supported yet.

Running the examples

bot4s.telegram uses mill.

$ mill examples.jvm[2.12.13].console
[79/79] examples.jvm[2.12.13].console
Welcome to Scala 2.12.13 (OpenJDK 64-Bit Server VM, Java 11.0.10).
Type in expressions for evaluation. Or try :help.

scala> new RandomBot("BOT_TOKEN").run()

Change RandomBot to whatever bot you find interesting here.

A note on implicits

A few implicits are provided to reduce boilerplate, but are discouraged because unexpected side-effects.

Think seamless T => Option[T] conversion, Markdown string extensions (these are fine)...
Be aware that, for conciseness, most examples need the implicits to compile, be sure to include them.

import com.bot4s.telegram.Implicits._

Examples

RandomBot! (full example)

import cats.instances.future._
import cats.syntax.functor._
import com.bot4s.telegram.api.RequestHandler
import com.bot4s.telegram.api.declarative.Commands
import com.bot4s.telegram.clients.{FutureSttpClient, ScalajHttpClient}
import com.bot4s.telegram.future.{Polling, TelegramBot}
import slogging.{LogLevel, LoggerConfig, PrintLoggerFactory}

import scala.util.Try
import scala.concurrent.Future

/** Generates random values.
  */
class RandomBot(val token: String) extends TelegramBot
  with Polling
  with Commands[Future] {

  LoggerConfig.factory = PrintLoggerFactory()
  // set log level, e.g. to TRACE
  LoggerConfig.level = LogLevel.TRACE

  // Use sttp-based backend
  implicit val backend = SttpBackends.default
  override val client: RequestHandler[Future] = new FutureSttpClient(token)

  // Or just the scalaj-http backend
  // override val client: RequestHandler[Future] = new ScalajHttpClient(token)

  val rng = new scala.util.Random(System.currentTimeMillis())
  onCommand("coin" or "flip") { implicit msg =>
    reply(if (rng.nextBoolean()) "Head!" else "Tail!").void
  }
  onCommand('real | 'double | 'float) { implicit msg =>
    reply(rng.nextDouble().toString).void
  }
  onCommand("/dice" | "roll") { implicit msg =>
    reply("⚀⚁⚂⚃⚄⚅" (rng.nextInt(6)).toString).void
  }
  onCommand("random" or "rnd") { implicit msg =>
    withArgs {
      case Seq(Int(n)) if n > 0 =>
        reply(rng.nextInt(n).toString).void
      case _ => reply("Invalid argumentヽ(ಠ_ಠ)ノ").void
    }
  }
  onCommand('choose | 'pick | 'select) { implicit msg =>
    withArgs { args =>
      replyMd(if (args.isEmpty) "No arguments provided." else args(rng.nextInt(args.size))).void
    }
  }

  // Int(n) extractor
  object Int {
    def unapply(s: String): Option[Int] = Try(s.toInt).toOption
  }
}

 
// To run spawn the bot
val bot = new RandomBot("BOT_TOKEN")
val eol = bot.run()
println("Press [ENTER] to shutdown the bot, it may take a few seconds...")
scala.io.StdIn.readLine()
bot.shutdown() // initiate shutdown
// Wait for the bot end-of-life
Await.result(eol, Duration.Inf)

Google TTS (full example)

import java.net.URLEncoder

import cats.instances.future._
import cats.syntax.functor._
import com.bot4s.telegram.Implicits._
import com.bot4s.telegram.api.declarative._
import com.bot4s.telegram.api.ChatActions
import com.bot4s.telegram.future.Polling
import com.bot4s.telegram.methods._
import com.bot4s.telegram.models._

import scala.concurrent.Future

/** Text-to-speech bot (using Google TTS API)
  *
  * Google will rightfully block your IP in case of abuse.
  * Usage: /speak Hello World
  */
object TextToSpeechBot extends TelegramBot
  with Polling
  with Commands[Future]
  with InlineQueries[Future]
  with ChatActions[Future] {
  
  override val client: RequestHandler[Future] = new ScalajHttpClient("BOT_TOKEN")
  
  def ttsUrl(text: String): String =
    s"http://translate.google.com/translate_tts?client=tw-ob&tl=en-us&q=${URLEncoder.encode(text, "UTF-8")}"

  onCommand("speak" | "say" | "talk") { implicit msg =>
    withArgs { args =>
      val text = args.mkString(" ")
      for {
        r <- Future { scalaj.http.Http(ttsUrl(text)).asBytes }
        if r.isSuccess
        bytes = r.body
        _ <- uploadingAudio // hint the user
        voiceMp3 = InputFile("voice.mp3", bytes)
        _ <- request(SendVoice(msg.source, voiceMp3))
      } yield ()
    }
  }
}

val bot = TextToSpeechBot
val eol = bot.run()
println("Press [ENTER] to shutdown the bot, it may take a few seconds...")
scala.io.StdIn.readLine()
bot.shutdown() // initiate shutdown
// Wait for the bot end-of-life
Await.result(eol, Duration.Inf) // ScalaJs wont't let you do this

Using webhooks

object LmgtfyBot extends AkkaTelegramBot
  with Webhook
  with Commands[Future] {
  
  val client = new AkkaHttpClient("BOT_TOKEN")  
  override val port = 8443
  override val webhookUrl = "https://1d1ceb07.ngrok.io"
  
  onCommand("lmgtfy") { implicit msg =>
    withArgs { args =>
      reply(
        "http://lmgtfy.com/?q=" + URLEncoder.encode(args.mkString(" "), "UTF-8"),
        disableWebPagePreview = Some(true)
      )
    }
  }
}

Check out the sample bots for more functionality.

Versioning

This library uses Semantic Versioning. For the versions available, see the tags on this repository.

Authors

  • Alfonso² Peterssen - Owner/maintainer - mukel

Looking for maintainers!

See also the list of awesome contributors who participated in this project. Contributions are very welcome, documentation improvements/corrections, bug reports, even feature requests.

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Buy Me A Coffee

Buy Me A Coffee

If you like this library, please consider buying me a coffee. ☺️

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].