node.js gbk编码_如何使用Node.js将Chrome的霸王龙编码为电报游戏

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)

翻译自: https://www.freecodecamp.org/news/how-to-code-chromes-t-rex-as-a-telegram-game-using-node-js-cbcf42f76f4b/

node.js gbk编码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值