node.js gbk編碼
by Fernando García álvarez
通過費爾南多·加西亞·阿爾瓦雷斯
如何使用Node.js將Chrome的霸王龍編碼為電報游戲 (How to code Chrome’s T-Rex as a Telegram game using Node.js)
Last month I was really interested in learning how the Telegram game platform works. And as I was also really bored of playing Chrome’s T-Rex game alone, I decided to make it work as a Telegram game.
上個月,我對學習Telegram游戲平臺的工作方式非常感興趣。 而且,由于我也對獨自玩Chrome的T-Rex游戲感到非常無聊,因此我決定將其作為Telegram游戲使用。
While developing it I noticed there weren’t many Telegram game bot tutorials. Tutorial would explain the whole process of building it, from start to finish. So I decided to write about it.
在開發它時,我注意到并沒有太多Telegram游戲機器人教程。 教程將從頭到尾說明構建它的整個過程。 因此,我決定寫這篇文章。
If you want to see the result, the game is available as trexjumpbot in Telegram and is hosted here.
如果您想查看結果,可以在Telegram中以trexjumpbot的形式獲得該游戲, 并在此處托管。
要求 (Requirements)
You need to have Node.js installed
您需要安裝Node.js
第1步:創建我們的機器人 (Step 1: Creating our bot)
In order to create a game, we must first create an inline bot. We do this by talking to BotFather and sending the command
為了創建游戲,我們必須首先創建一個嵌入式機器人。 我們通過與BotFather交談并發送命令來做到這一點
/newbot
/newbot
Then, we are asked to enter a name and a username for our bot and we are given an API token. We need to save it as we will need it later.
然后,要求我們輸入機器人的名稱和用戶名,并獲得一個API令牌。 我們需要保存它,因為稍后將需要它。
We can also complete our bot info by changing its description (which will be shown when a user enters a chat with our bot under the “What can this bot do?” section) with
我們還可以通過更改其說明(當用戶在“此機器人可以做什么?”部分下與我們的機器人進行聊天時顯示)來完成我們的機器人信息。
/setdescription
/setdescription
And also set its picture, in order to make it distinguishable from the chat list. The image must be square and we can set it with the following command:
并設置其圖片,以使其與聊天列表區分開。 圖片必須為正方形,我們可以使用以下命令進行設置:
/setuserpic
/setuserpic
We can also set the about text, which will appear on the bot’s profile page and also when sharing it with other users
我們還可以設置About文本,該文本將顯示在機器人的個人資料頁面上以及與其他用戶共享時
/setabouttext
/setabouttext
Our bot has to be inline in order to be able to use it for our game. In order to do this, we simply have to execute the following and follow the instructions
我們的機器人必須是內聯的,以便能夠在我們的游戲中使用它。 為此,我們只需執行以下步驟并按照說明進行操作
/setinline
/setinline
步驟2:建立游戲 (Step 2: Creating our game)
Now that we have our inline bot completely set up, it’s time to ask BotFather to create a game:
現在我們已經完全設置了內聯機器人,現在是時候讓BotFather創建游戲了:
/newgame
/newgame
We simply follow the instructions and finally we have to specify a short name for our game. This will act as a unique identifier for it, which we will need later along with our bot API token
我們只需按照說明進行操作,最后我們必須為我們的游戲指定一個簡短的名稱。 這將充當它的唯一標識符,我們稍后將需要它以及bot API令牌
步驟3:獲取T-Rex游戲源代碼 (Step 3: Getting T-Rex game source code)
As Chromium is open source, some users have extracted the T-Rex game from it and we can easily find its source code online.
由于Chromium是開源的,因此一些用戶已經從中提取了T-Rex游戲,我們可以輕松地在網上找到其源代碼。
In order to make the game, I have used the code available in this GitHub repo, so go ahead and clone it:
為了制作游戲,我使用了此GitHub存儲庫中可用的代碼,因此繼續進行克隆:
git clone https://github.com/wayou/t-rex-runner.git
步驟4:設置依賴關系 (Step 4: Setting up dependencies)
First, go into the cloned folder and move all its files into a new folder called “public”
首先,進入克隆的文件夾,并將其所有文件移動到名為“ public”的新文件夾中
mkdir public && mv * public/.
And init the project
并啟動項目
npm init
You can fill the requested info as you want (you can leave the default values), leave the entry point as index.js
您可以根據需要填寫所需的信息(可以保留默認值),將入口點保留為index.js
We will need Express and node-telegram-bot-api in order to easily interact with Telegram’s API
我們將需要Express和node-telegram-bot-api以便輕松與Telegram的API進行交互
npm install express --savenpm install node-telegram-bot-api --save
We are going to add a start script, since it’s necessary in order to deploy the game to Heroku. Open package.json and add the start script under the scripts section:
我們將添加一個啟動腳本,因為將游戲部署到Heroku是必需的。 打開package.json并在腳本部分下添加啟動腳本:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
}
第5步:對服務器進行編碼 (Step 5: Coding our server)
Now that we have all dependencies set up, it’s time to code the server for our bot. Go ahead and create the index.js file:
現在我們已經設置了所有依賴項,是時候為我們的機器人編寫服務器代碼了。 繼續創建index.js文件:
const express = require("express");
const path = require("path");
const TelegramBot = require("node-telegram-bot-api");
const TOKEN = "YOUR_API_TOKEN_GOES_HERE";
const server = express();
const bot = new TelegramBot(TOKEN, { polling: true } );
const port = process.env.PORT || 5000;
const gameName = "SHORT_NAME_YOUR_GAME";
const queries = {};
The code above is pretty straightforward. We simply require our dependencies and set the token we got from BotFather and also the short name we defined as the game identifier. Also, we set up the port, initialize Express and declare a queries empty object. This will act as a map to store the Telegram user object under his id, in order to retrieve it later.
上面的代碼非常簡單。 我們只需要我們的依賴關系,并設置從BotFather獲得的令牌,以及我們定義為游戲標識符的簡稱。 同樣,我們設置端口,初始化Express并聲明一個查詢為空的對象。 這將用作將電報用戶對象存儲在其ID下的映射,以便以后檢索。
Next, we need to make the contents of the public directory available as static files
接下來,我們需要將公共目錄的內容作為靜態文件提供
server.use(express.static(path.join(__dirname, 'public')));
Now we are going to start defining our bot logic. First, let’s code the /help command
現在,我們將開始定義機器人邏輯。 首先,讓我們編寫/ help命令的代碼
bot.onText(/help/, (msg) => bot.sendMessage(msg.from.id, "This bot implements a T-Rex jumping game. Say /game if you want to play."));
We have to specify the command as a regex on the first parameter of onText and then specify the bot’s reply with sendMessage. Note we can access the user id in order to reply by using msg.from.id
我們必須在onText的第一個參數上將命令指定為正則表達式,然后使用sendMessage指定漫游器的回復。 請注意,我們可以使用msg.from.id來訪問用戶ID以便進行回復
When our bot receives the /start or /game command we are going to send the game to the user using bot.sendGame
當我們的機器人收到/ start或/ game命令時,我們將使用bot.sendGame將游戲發送給用戶
bot.onText(/start|game/, (msg) => bot.sendGame(msg.from.id, gameName));
Now the user will be shown the game’s title, his high score and a button to play it, but the play button still doesn’t work. So, we are going to implement its logic
現在,將向用戶顯示游戲的標題,他的高分和一個播放游戲的按鈕,但是播放按鈕仍然不起作用。 因此,我們將執行其邏輯
bot.on("callback_query", function (query) {
if (query.game_short_name !== gameName) {
bot.answerCallbackQuery(query.id, "Sorry, '" + query.game_short_name + "' is not available.");
} else {
queries[query.id] = query;
let gameurl = "https://YOUR_URL_HERE/index.html? id="+query.id;
bot.answerCallbackQuery({
callback_query_id: query.id,
url: gameurl
});
}
});
When the user clicks the play button Telegram sends us a callback. In the code above when we receive this callback first we check that the requested game is, in fact, our game, and if not we show an error to the user.
當用戶單擊播放按鈕時,Telegram向我們發送回叫。 在上面的代碼中,當我們首先收到此回調時,我們檢查所請求的游戲是否確實是我們的游戲,如果沒有,則向用戶顯示錯誤。
If all is correct, we store the query into the queries object defined earlier under its id, in order to retrieve it later to set the high score if necessary. Then we need to answer the callback by providing the game’s URL. Later we are going to upload it to Heroku so you’ll have to enter the URL here. Note that I’m passing the id as a query parameter in the URL, in order to be able to set a high score.
如果一切正確,我們會將查詢存儲到先前在其ID下定義的查詢對象中,以便稍后進行檢索以在必要時設置高分。 然后,我們需要通過提供游戲的網址來回答回調。 稍后,我們將其上傳到Heroku,因此您必須在此處輸入URL。 請注意,我將id作為查詢參數傳遞給URL,以便能夠設置較高的分數。
Right now we have a fully functional game but we still are missing high scores and inline behavior. Let’s start with implementing inline and offering our game:
目前,我們有一個功能齊全的游戲,但我們仍然缺少高分和內聯行為。 讓我們從內聯實現和提供游戲開始:
bot.on("inline_query", function(iq) {
bot.answerInlineQuery(iq.id, [ { type: "game", id: "0", game_short_name: gameName } ] );
});
Last, we are going to implement the high score logic:
最后,我們將實現高分邏輯:
server.get("/highscore/:score", function(req, res, next) {
if (!Object.hasOwnProperty.call(queries, req.query.id)) return next();
let query = queries[req.query.id];
let options;
if (query.message) {
options = {
chat_id: query.message.chat.id,
message_id: query.message.message_id
};
} else {
options = {
inline_message_id: query.inline_message_id
};
}
bot.setGameScore(query.from.id, parseInt(req.params.score), options,
function (err, result) {});
});
In the code above, we listen for URLs like /highscore/300?id=5721. We simply retrieve the user from the queries object given its id (if it exists) and the use bot.setGameScore to send the high score to Telegram. The options object is different if the user is calling the bot inline or not, so we check both situations as defined in the Telegram Bot API
在上面的代碼中,我們偵聽/ highscore / 300?id = 5721之類的URL。 我們只需從查詢對象中檢索給定其ID(如果存在)的用戶,并使用bot.setGameScore將高分發送給Telegram。 如果用戶是否內聯調用bot,options對象是不同的,因此我們檢查了Telegram Bot API中定義的兩種情況
The last thing we have to do on our server is to simply listen in the previously defined port:
我們在服務器上要做的最后一件事就是簡單地偵聽先前定義的端口:
server.listen(port);
第6步:修改霸王龍游戲 (Step 6: Modifying T-Rex game)
We have to modify the T-Rex game we cloned from the GitHub repo in order for it to send the high score to our server.
我們必須修改從GitHub存儲庫中克隆的T-Rex游戲,以將高分發送給我們的服務器。
Open the index.js file under the public folder, and at the top of it add the following lines in order to retrieve the player id from the url:
打開公用文件夾下的index.js文件,并在其頂部添加以下行,以便從url中檢索播放器ID:
var url = new URL(location.href);
var playerid = url.searchParams.get("id");
Last, we are going to locate the setHighScore function and add the following code to the end of it, in order to submit the high score to our server:
最后,我們將定位setHighScore函數并將以下代碼添加到它的末尾,以便將高分提交給我們的服務器:
// Submit highscore to Telegram
var xmlhttp = new XMLHttpRequest();
var url = "https://YOUR_URL_HERE/highscore/" + distance +
"?id=" + playerid;
xmlhttp.open("GET", url, true);
xmlhttp.send();
步驟7:部署到Heroku (Step 7: Deploying to Heroku)
Our game is complete, but without uploading it to a server we can’t test it on Telegram, and Heroku provides us a very straightforward way to upload it.
我們的游戲已經完成,但是沒有將其上傳到服務器,就無法在Telegram上對其進行測試,而Heroku為我們提供了一種非常簡單的上傳方式。
Start by creating a new app:
首先創建一個新應用:
Change our URL placeholders with the actual URL (replace with your own):
用實際的URL更改我們的URL占位符(用您自己的URL代替):
Replace the URL with the setHighScore function
用setHighScore函數替換URL
var url = "https://trexgame.herokuapp.com/highscore/" + distance +
"?id=" + playerid;
And also on the callback on the server:
以及服務器上的回調:
let gameurl = "https://trexgame.herokuapp.com/index.html?id="+query.id;
Finally, let’s upload our game to Heroku. Let’s follow the steps detailed on the Heroku page: After installing Heroku CLI, from the project folder login and push the files:
最后,讓我們將游戲上傳到Heroku。 讓我們按照Heroku頁面上詳述的步驟進行操作:安裝Heroku CLI后 ,從項目文件夾登錄并推送文件:
heroku logingit initheroku git:remote -a YOUR_HEROKU_APP_NAMEgit add .git commit -m "initial commit"git push heroku master
And that’s it!, now you finally have a fully working Telegram game. Go ahead and try it!
就是這樣!現在,您終于有了一個可以正常運行的Telegram游戲。 繼續嘗試!
Full source code of this example is available on GitHub
該示例的完整源代碼可在GitHub上找到
參考文獻 (References)
http://wimi5.com/como-crear-un-bot-para-juegos-en-telegram-con-nodejs/
http://wimi5.com/como-crear-un-bot-para-juegos-en-telegram-con-nodejs/
https://core.telegram.org/bots/api#setgamescore
https://core.telegram.org/bots/api#setgamescore
https://github.com/wayou/t-rex-runner
https://github.com/wayou/t-rex-runner
翻譯自: https://www.freecodecamp.org/news/how-to-code-chromes-t-rex-as-a-telegram-game-using-node-js-cbcf42f76f4b/
node.js gbk編碼