banner
niracler

niracler

长门大明神会梦到外星羊么?
github
email
steam_profiles
douban
nintendo switch
tg_channel
twitter_id

Simple and Easy-to-Understand Telegram to xLog Shorts Bot Deployment Plan - v1.0

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 implemented for half a month, but I have been procrastinating on writing this article to introduce how to deploy it. 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)
image

Preparation#

Install Wrangler and log in to Cloudflare account#

Cloudflare Workers is a serverless service provided by Cloudflare. Our bot (which I call 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 as well, such as:

  1. The free version of Cloudflare Workers has a quota of 100,000 requests per day, which is sufficient for personal use.
  2. It eliminates the operational costs of setting up your own server.
  3. You can access the Telegram API without needing to set up 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, completing the first step 🎉

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 the example below, for instance, my bot's username here is xlog_20240110_bot)

image

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:

  1. xLog's token
  2. 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

(Illustration, if there is a simpler way, please be sure to let me know~~)
image

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 to 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 = "..."

Here is the template; we will first create a D1 database and then fill in 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 able to sync to xLog due to the absence of the corresponding media_group_id in the D1 database. I will consider making a script to sync 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's environment variables. These three are the bot's token, xLog's token, and xLog's characterId.

Execute the following commands in sequence to set these three keys into the Cloudflare worker's 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 try to 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 if 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, so you 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 for a bit.

image

Register Nyaruko's commands (optional)#

For convenience, we can register Nyaruko's commands. On TG:

  1. Find Botfather
  2. Type /setcommands, then select your bot
  3. 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 (逃)#

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 to TG and test sending messages to xLog. 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 picture message to test with Nyaruko.)
image

Postscript#

I feel like it took a long time to write this tutorial; I even refactored the code. I feel like I didn't do much, but I spent a lot of time. I can easily be the kind of person who builds things in isolation, 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 selection looks like this#

It's definitely not because I can only write TypeScript (逃).

  1. Cloudflare is free, and you can access the Telegram API without needing to set up a proxy.
  2. The SDK for crossbell is in TypeScript, and 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, more details about Nyaruko's other functions can be found at:

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 first, which is also 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
  • Usable account list; in fact, CHARACTER_ID can also be an array.
  • There may be situations where the blockchain wallet has insufficient funds.

Some random thoughts#

  • When writing documentation, try to use code blocks whenever possible instead of images, as it makes copying and pasting easier.
  • I also tried not to take any screenshots of Cloudflare throughout, so everything can be operated in the command line.

References#

  • [From a technical perspective, tinkering with xlog] A smoother user experience 2 In-depth understanding of xlog's authentication](https://blog.ijust.cc/play-xlog-02) - Xinbao Otto's xlog tutorial, very detailed, and there are video tutorials~~
  • ChatGPT-Telegram-Bot - Another TG Bot project, written by a younger predecessor than me.
  • Official Wrangler Documentation - The wrangler documentation feels much easier to understand than the Twitter documentation, at least there are many more examples~~
  • Telegram Bot API - Telegram Bot API documentation
Cover image

Cheers

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.