Perhaps, it's not very straightforward, and it might take about 30 minutes to complete the operation.
Recently, I wrote a TG bot that can automatically forward TG messages as xLog Shorts. The functionality has been completed for half a month, but I have been delaying writing this article on how to deploy it until now. I still feel quite anxious about it.
Specific technology: Cloudflare Worker + Telegram Bot API + xLog Shorts. In short, it's free.
Note
If you have any questions, feel free to raise an issue or a PR. Please provide feedback; generally, there will be a response within 48 hours.
(Effect picture)
Preparation#
Install Wrangler and log in to your Cloudflare account#
Cloudflare Workers is a serverless service provided by Cloudflare. Our bot (I call her Nyaruko) and this project (her life) are deployed (alive) on this platform. I chose Workers because I need it for my main job, so I thought I would practice a bit 🤣. Of course, there are some legitimate reasons, such as:
- The free version of Cloudflare Workers allows for 100,000 requests per day, which is more than enough for personal use.
- It eliminates the operational costs of setting up your own server.
- You can access the Telegram API without needing a proxy.
Wrangler is an official command-line tool provided by Cloudflare for deploying Cloudflare Workers. You can refer to the official documentation for installing Wrangler and logging into your Cloudflare account.
If you don't have a Cloudflare account, you can take this opportunity to register (link)
If you don't have Node.js, you can also install it (link)
We execute the following command here, and we have successfully logged in; the first step is complete 🎉
npm install -g wrangler
wrangler login
Confirm the login is complete with wrangler woami
$ wrangler whoami
⛅️ wrangler 3.23.0
-------------------
Getting User settings...
👋 You are logged in with an OAuth Token, associated with the email [email protected]!
┌────────────────────────┬──────────────────────────────────┐
│ Account Name │ Account ID │
├────────────────────────┼──────────────────────────────────┤
│ [email protected]'s Account │ *** │
└────────────────────────┴──────────────────────────────────┘
🔓 Token Permissions: If scopes are missing, you may need to logout and re-login.
Scope (Access)
- account (read)
- user (read)
- workers (write)
- workers_kv (write)
- workers_routes (write)
- workers_scripts (write)
- workers_tail (read)
- d1 (write)
- pages (write)
- zone (read)
- ssl_certs (write)
- constellation (write)
- ai (read)
- offline_access
Apply for a Telegram Bot API token#
Next, we need to find Botfather to apply for a TG bot. You can refer to the official documentation for applying for a TG bot.
(Just like below, for example, my bot's username here is xlog_20240110_bot)
Obtain xLog's Token and CharacterId#
At this point, we turn our attention to xLog. Refer to Xinbao Otto for the token acquisition tutorial. We need to obtain the following two items:
- xLog's token
- xLog's characterId
On the xSettings page, click on the current character, and enter the following code in the browser's console:
JSON.parse(localStorage.getItem('connect-kit:account')).state.wallet.siwe.token
JSON.parse(localStorage.getItem('connect-kit:account')).state.wallet.characterId
(Schematic diagram, if there is a simpler way, please let me know~~)
Start Deployment#
Ahem, it's finally time to deploy. Without further ado, let's get started.
Clone and enter the project directory#
Yes, it's that simple. Run the following command in the terminal: clone -> enter the project directory -> install dependencies. (To ensure the usability of this tutorial, I specified the exact version v0.2.3 when cloning.)
git clone https://github.com/niracler/nyaruko-telegram-bot -b "v0.2.3"
cd nyaruko-telegram-bot
npm install
Generate configuration file#
I have a demo configuration file, and we will copy it here (in the code block, lines not starting with $
are the command output results).
$ cp wrangler.demo.toml wrangler.toml
$ cat wrangler.toml
name = "nyaruko-telegram-bot"
main = "src/index.ts"
compatibility_date = "2023-11-21"
compatibility_flags = [ "nodejs_compat" ]
[vars]
ALLOW_USER_IDS = [ ]
TELEGRAM_BOT_USERNAME = ''
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "tg"
database_id = "..."
The template is here; let's create a D1 database first, and then fill out this configuration file.
Create D1 Database#
Since the information of media_group is stored in the D1 database, we need to create a D1 database.
Note ⚠️: Messages with multiple images before Nyaruko is deployed will not be synchronized to xLog because the corresponding media_group_id cannot be found in the D1 database. I will consider creating a script to synchronize historical messages later.
Execute the following command to create a D1 database.
wrangler d1 create tg
Then fill in the name of the returned D1 database into wrangler.toml
, changing the database_id in my configuration file to your D1 database id. Fill in the database_id output from the command into the wrangler.toml
above.
[[d1_databases]]
binding = "DB" # i.e. available in your Worker on env.DB
database_name = "tg"
database_id = "******"
Execute the following command to create the D1 database table (make sure to change the database_id in wrangler.toml
first).
wrangler d1 execute tg --file=./schema.sql
Set various keys#
Next, we need to set the various keys from the "Preparation" section into the Cloudflare Worker environment variables. These three are the bot's token, xLog's token, and xLog's characterId.
Execute the following commands in order to set these three keys into the Cloudflare Worker environment variables (note, do not include extra quotes for XLOG_TOKEN).
wrangler secret put TELEGRAM_BOT_SECRET
wrangler secret put XLOG_TOKEN
wrangler secret put XLOG_CHARACTER_ID
Deploy to Cloudflare Worker#
Alright, we can now deploy Nyaruko to Cloudflare Worker. (Execute the following command; in the code block, lines not starting with $
are the command output results.)
$ wrangler deploy
⛅️ wrangler 3.23.0
-------------------
Your worker has access to the following bindings:
- D1 Databases:
- DB: tg (******)
- Vars:
- ALLOW_USER_IDS: []
- TELEGRAM_BOT_USERNAME: ""
Total Upload: 708.56 KiB / gzip: 123.29 KiB
Uploaded nyaruko-telegram-bot (2.52 sec)
Published nyaruko-telegram-bot (3.91 sec)
https://your-worker.your-name.workers.dev
Current Deployment ID: ******
Set Nyaruko's Webhook#
Set Nyaruko's Webhook to your Cloudflare Workers address (which is in the output of the above command); Nyaruko needs to receive messages via Webhook.
Execute the following command (be sure to replace https://your-worker.your-name.workers.dev/
and TELEGRAM_BOT_SECRET
with your own).
curl -F "url=https://your-worker.your-name.workers.dev/" https://api.telegram.org/bot<TELEGRAM_BOT_SECRET>/setWebhook
Then confirm whether the Webhook is set successfully by executing the following command (be sure to replace TELEGRAM_BOT_SECRET
with your own).
$ curl https://api.telegram.org/bot<TELEGRAM_BOT_SECRET>/getWebhookInfo
{"ok":true,"result":{"url":"https://nyaruko-telegram-bot.***.workers.dev/","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"******"}}
PS. The api.telegram.org may be blocked, and you will need to use a command-line proxy. If you don't know how to handle it, feel free to contact me.
You can also chat with Nyaruko.
Register Nyaruko's commands (optional)#
For convenience, we can register Nyaruko's commands. On TG:
- Find Botfather
- Enter
/setcommands
, then select your bot - Enter the following content:
sync_xlog - Sync msg to Twitter.
ping - Test if the bot is online.
getchatid - Get the ID of the current chat.
getuserid - Get the ID of the current user.
Subsequently, command completion will be available.
Configure ALLOW_USER_IDS to let Nyaruko know you are her master (escape)#
Yes, we can't let everyone use Nyaruko to forward your TG messages. So we need to fill in our TG id into the ALLOW_USER_IDS in wrangler.toml
. This way, Nyaruko will know you are her master. (This is the output of the getuserid command above.)
[vars]
ALLOW_USER_IDS = [ "******" ]
Then run wrangler deploy
again.
Completion and Celebration#
Alright, it's done. Now you can go test sending messages to xLog on TG. Nyaruko will take the first sentence as the title of the Short and the rest as the content of the Short.
(I found a prehistoric image message to test with Nyaruko)
Postscript#
It feels like I've been writing this tutorial for a long time; I've even refactored the code. I feel like I haven't done much, but I've spent a lot of time. I'm easily the kind of person who can reinvent the wheel, so the code quality of this project might not be very good. If you have any questions, feel free to raise an issue or a PR. Please provide feedback; generally, there will be a response within 48 hours.
About why the technology stack looks like this#
It's definitely not because I can only write TypeScript (escape).
- Cloudflare is free, and you can access the Telegram API without needing a proxy.
- The SDK for crossbell is in TypeScript; if I used another language, I would have to manually implement the IPFS upload logic. (And it's definitely not just to make it easier to copy Xinbao's code.)
The long and winding road ahead#
How should I put it, Nyaruko has other functionalities that can be seen.
How to separate sync xlog for others to use, I haven't figured out the format yet. Originally, Nyaruko was designed as my all-in-one personal assistant. Now it seems that those interested might have to deploy Nyaruko entirely, isn't that a kind of NTR (bushi).
There are still some considerations, but I haven't thought them through yet (and I don't want to think about it, where's my weekend???).
- Debug mode
- List of usable accounts; in fact, CHARACTER_ID could also be an array.
- There might be cases where the blockchain wallet has insufficient funds.
Some random thoughts#
- When writing documentation, try to use code blocks whenever possible instead of images, as this makes it easier to copy and paste.
- I also tried not to take any screenshots of Cloudflare throughout, so that everything could be operated via the command line.
References#
- [Tinkering with xlog from a technical perspective] - A smoother user experience 2 Understanding xlog's authentication](https://blog.ijust.cc/play-xlog-02) - Xinbao Otto's xlog tutorial, written in great detail, and there are video tutorials too~~
- ChatGPT-Telegram-Bot - Another TG Bot project, written by a younger predecessor than me.
- Official Wrangler Documentation - The wrangler documentation seems to be much easier to understand than the Twitter documentation, at least there are many more examples~~
- Telegram Bot API - Telegram Bot API documentation
Cover Image