Telegram Fax

Printing a Fax using Telegram

On some day, I’ve come across a thermal printer on Tutti.ch (the swiss eBay). Inspired by a blog post on a GitHub issues printer, I’ve decided to buy it.

The printer is from Citizen, and the particular model I’ve found is CT-S801. According to their marketing, it’s one of the fastest thermal printers on the market. Do I need that functionality? No. Do I need a thermal printer at all? Also no, but… I’m currently writing my master thesis, so anything to procrastinate is highly welcome, and I have an unused Raspberry Pi laying around.

Now, I’ve decided to write something that would forward messages from Telegram to this printer. And since Go is the latest rage and programming language I currently hate the least, I’ve decided to write the program with that.

The printer understands ESC-POS which is great because there’s robust libraries around that help with that. I’ve found kng/escpos which does a great job. After connecting the printer to the Raspberry Pi using USB B (the cable that you get with your monitor but never use - finally a usecase!), the device would show up under /dev/usb/lp0. I had to give rw permission to the file using sudo chmod +666 /dev/usb/lp0 before I could actually use it:

// error handling and closing files omitted
f, _ := os.OpenFile("/dev/usb/lp0", os.O_RDWR, 0)
e := escpos.New(f)
e.Write("Oh hey cool, that works!")

To receive Telegram messages, there’s excellent API bindings. It’s super easy to use:

bot, _ := tgbotapi.NewBotAPI(token)
for update := range bot.GetUpdatesChan(tgbotapi.NewUpdate(0)) {
  e.Write(update.Message.Text)
}

Basically that’s already it! Now whenever somebody writes to my bot, the message is immediately printed. It’s crazy fast! I’m not using webhooks for Telegram, so I’m assuming it’s using Long Polling under the hood.

Now of course, before telling my friends about it, I had to put some basic abuse mechanisms in place. I’ve added rate-limiting (both per person and also globally) as well as restriction on the maximum message size. So far, it has been working great and I’ve received some lovely messages (including an excerpt from The Lord of the Rings and some ASCII drawing (attempts)).

The complete code can be found on Github.


Project

363 Words

2022-06-04 18:03 +0000