twitter id生成类

编程入门 行业动态 更新时间:2024-10-09 20:27:43

<a href=https://www.elefans.com/category/jswz/34/1771189.html style=twitter id生成类"/>

twitter id生成类

twitter id生成类

by Shawn Toubeau

肖恩·图博(Shawn Toubeau)

我如何构建可生成歌曲歌词的Twitter机器人 (How I built a Twitter bot that generates song lyrics)

In this article, I will go over how I built my Twitter lyric bot and how you’ll be able to set up your very own.

在本文中,我将介绍如何构建Twitter歌词机器人以及如何建立自己的Twitter歌词机器人。

程序 (Procedure)

Here’s a list of the components we have to set up.

这是我们必须设置的组件的列表。

  1. Twitter Account

    Twitter帐号
  2. Text Editor/IDE

    文字编辑器/ IDE
  3. The bot

    机器人
  4. Heroku Automation

    Heroku自动化

设置新的Twitter应用程序 (Setup New Twitter Application)

To create a new Twitter application, go here. You will need to apply for developer access. After you submit the application, it may take a while but Twitter will notify you when you get accepted.

要创建新的Twitter应用程序,请转到此处 。 您将需要申请开发人员访问权限。 提交申请后,可能需要一段时间,但Twitter会在您被接受时通知您。

设置编辑器/ IDE (Setup Editor/IDE)

Now you’re going to want to set up your editor. My preference is VS Code, so that’s what I’ll be using.

现在,您将要设置编辑器。 我的首选是VS Code,所以这就是我要使用的。

Make sure you have Git and Node installed.

确保已安装Git和Node。

Go ahead clone the following git repository to your computer.

继续将以下git存储库克隆到您的计算机。

git clone .git

码走槽 (Code Walk Trough)

The 3 main files that the bot consists of are bot.js, lyrics.txt, and .env.

机器人组成的3个主要文件是bot.js,lyrics.txt和.env。

SideNote: Your clone of the project will not contain a .env file because of the .gitignore, thus we will be creating our own later down in the article!

SideNote :由于.gitignore,您的项目克隆将不包含.env文件,因此,我们将在本文后面创建自己的文件!

bot.js (bot.js)

Starting in bot.js, we start by importing Twit, fs, and dotenv.

从bot.js开始,我们首先导入Twit,fs和dotenv。

Twit is a module that supports the Twitter Developer API.

Twit是支持Twitter Developer API的模块。

Fs, or file system, is a file I/O nodule that allows us to interact with our lyrics.txt file.

Fs或文件系统是一个文件I / O结点,它使我们可以与lyrics.txt文件进行交互。

Dotenv is a module that reads in environment variables stored in our .env file.

Dotenv是一个模块,可读取存储在.env文件中的环境变量。

const Twit = require('twit');
const fs = require('fs');
require('dotenv').config();
const order = 4; // length of each n-gram
let nGrams = {};
const Bot = new Twit({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

nGrams is the object that keeps track of substring occurrences so that we are able to use a probability to generate our own lyrics randomly. You can read more about them here.

nGrams是跟踪子字符串出现的对象,因此我们可以利用概率随机生成自己的歌词。 您可以在此处阅读有关它们的更多信息。

And Bot is…well...our Bot! We need to define some variables to make it work. Using the dotenv module, we can grab the values stored in our .env file.

Bot是...好吧...我们的Bot! 我们需要定义一些变量以使其工作。 使用dotenv模块,我们可以获取存储在.env文件中的值。

Next we define a few functions as follows:

接下来,我们定义一些函数,如下所示:

pickRandomStart() (pickRandomStart())
function pickRandomStart(lyrics) {
const random = Math.floor(Math.random()*lyrics.length)
return lyrics.substring(random, random + order)
}

This selects the starting point for where we grab our first n-gram.

这将选择我们抓取第一个n-gram的起点。

makeEngramModel() (makeEngramModel())
function makeEngramModel(lyrics) {
for (let i = 0; i < lyrics.length - order; i++) {
const gram = lyrics.substring(i, i + order);
if (!nGrams[gram]) {
nGrams[gram] = [];
}
nGrams[gram].push(lyrics.charAt(i + order));
}
}

This creates the model that tracks the order and occurrences of all the n-grams parsed from the lyrics. By using the number of occurrences as the n-gram’s probability, it allows us to generate new lyrics in a random order.

这将创建一个模型,该模型跟踪从歌词中解析的所有n元语法的顺序和出现情况。 通过使用出现次数作为n-gram的概率,它使我们能够以随机顺序生成新歌词。

鸣叫() (tweet())
function tweet() {
fs.readFile('lyrics.txt', 'utf8', function(error, lyrics) {
if (error) {
console.log(error.message);
} else {
makeEngramModel(lyrics);
let currentGram = pickRandomStart(lyrics);
// checks to see if the start of the tweet doesn't start
// with punctuation or special characters and ends with a space
while (!currentGram.match(/^[0-9a-zA-Z]+$/)) {
currentGram = pickRandomStart(lyrics);
}
let tweet = currentGram;
// runs until char limit is reached while finishing the last word it was on
for (let j = 0; (j < 150) || (tweet.charAt(j).match(/^[0-9a-zA-Z]+$/)); j++) {
const possibilities = nGrams[currentGram];
const next = possibilities[Math.floor(Math.random()*possibilities.length)];
tweet += next;
const len = tweet.length;
currentGram = tweet.substring(len-order, len);
}
console.log(tweet)
Bot.post('statuses/update', {status: tweet}, function(error, tweet, response) {
if (error) {
console.log("Error making post. ", error.message);
};
});
}
});
}

Last but not least, this is the part that interacts with the bot. It starts by reading in the lyrics using the fs module and then it create the n-gram model using the lyrics variable. It selects a random starting point to use as the first n-gram which will be the start of the new lyrics. It performs a check to see whether the first n-gram contains only alphanumeric characters, because then it has a higher chance to start somewhat more sensical.

最后但并非最不重要的一点是,这是与机器人进行交互的部分。 首先使用fs模块读取歌词,然后使用lyrics变量创建n元语法模型。 它选择一个随机起点作为第一个n-gram,它将作为新歌词的开始。 它执行检查以查看第一个n-gram是否仅包含字母数字字符,因为这样,它有较高的机会开始更有意义。

It then chains randomly selected n-grams that pair with the last n-gram added to the tweet variable. It does this for at least 150 characters and like before, performs a check to see if it will end on an alphanumeric n-gram. If it does not end on a alphanumeric n-gram, it then will keep chaining from the model until it does.

然后,它将随机选择的n-gram与最后添加到tweet变量中的n-gram配对。 它至少要处理150个字符,并且像以前一样执行一次检查,看它是否以字母数字n-gram结尾。 如果它不是以字母数字n-gram结尾,则它将继续从模型进行链接,直到出现为止。

And finally the bot makes a post request with the lyrics as the tweet payload.

最终,机器人发出了以歌词为鸣叫有效载荷的发布请求。

Now that we have a good idea how how our code works, run the following command:

既然我们已经很好地了解了代码的工作方式,请运行以下命令:

npm install

in the lyric-bot project folder.

在lyric-bot项目文件夹中。

This installs the necessary modules () // and explains what npm install does.

这将安装必要的模块()//,并说明npm install的作用。

组态 (Configuration)

Now you’ll want to copy in a set of lyrics into the lyrics.txt file.

现在,您需要将一组歌词复制到lyrics.txt文件中。

Then create a .env file. This will store your Twitter API tokens.

然后创建一个.env文件。 这将存储您的Twitter API令牌。

Inside the new file, paste the following:

在新文件中,粘贴以下内容:

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=

and copy the respective tokens from your app’s developer console, once you get your developer application approved.

并在您的开发人员应用程序获得批准后,从应用程序的开发人员控制台复制相应的令牌。

Time to test it!

是时候测试了!

Type

类型

node bot.js

And take a look at the console!

看看控制台!

And check out the Twitter account too, of course:

当然,也请查看Twitter帐户:

塔达! (TA DA!)

You now have a working twitter bot that is able to post newly generated song lyrics! ?

您现在拥有一个可以正常工作的Twitter机器人,该机器人可以发布新生成的歌曲歌词! ?

Hold on though, we still have to automate it…

等等,尽管如此,我们仍然必须使其自动化……

Heroku部署 (Heroku Deployment)

Go over to Heroku and login. If you don’t have an account, you can create a free one! ?

转到Heroku并登录。 如果您没有帐户,则可以创建一个免费帐户!

Now, from the main dashboard, create a new app by clicking New->Create new app.

现在,从主仪表板中,通过单击“新建”->“创建新应用”来创建一个新应用。

Enter an available name then click Create App.

输入可用名称,然后单击创建应用程序。

Here is your app’s main control panel!

这是您应用的主控制面板!

If you scroll down in the ‘Deploy’ tab, you will see instructions for ‘Deploy using Heroku Git’. Follow the steps here, and once you’ve successfully deployed your app continue on to the next step.

如果在“部署”选项卡中向下滚动,则会看到有关“使用Heroku Git部署”的说明。 请按照此处的步骤操作,成功部署应用程序后,请继续执行下一步。

自动化 (Automation)

Go over to the ‘Overview’ tab and click ‘Configure Add-Ons’. Then, in the add-on search bar, type ‘ Heroku Scheduler’ and select it. A dialog will pop-up, hit ‘Provision’.

转到“概述”选项卡,然后单击“配置加载项”。 然后,在附加搜索栏中,键入“ Heroku Scheduler”并选择它。 将会弹出一个对话框,点击“ Provision”。

Once added, you can then click on the add-on and create these things called ‘jobs’. Jobs are essentially tasks that get executed by Heroku Scheduler.

添加完成后,您可以单击加载项并创建名为“ jobs”的东西。 作业本质上是由Heroku Scheduler执行的任务。

You’ll want to click ‘Add new job’ and a configure window will appear. In the command option, type the following:

您需要单击“添加新作业”,然后会出现一个配置窗口。 在命令选项中,键入以下内容:

node bot.js

and select the frequency you want to run the command. Once done click save.

并选择您要运行命令的频率。 完成后,单击保存。

And with that you have successfully deployed a Twitter lyric bot! ?

至此,您已经成功部署了Twitter歌词机器人! ?

致谢 (Acknowledgments)

Most of the code for creating the custom text is credited to Daniel Shiffman. You can find his material here!

用于创建自定义文本的大多数代码都归功于Daniel Shiffman。 你可以在这里找到他的资料!

The lyric data I used in this article was sampled from a song called Daylily by Movements.

我在本文中使用的歌词数据是从Movements的一首名为Daylily的歌曲中采样的。

Big thank you to Morgan Allgrove-Hodges for giving feedback and fixing my silly grammar mistakes! ?

非常感谢Morgan Allgrove-Hodges提供反馈并解决了我愚蠢的语法错误! ?

Connect with me on LinkedIn or follow me on Twitter! I love making new connections ?

在LinkedIn上与我联系或在Twitter上关注我! 我喜欢建立新的联系吗?

~ Shawn Toubeau

〜肖恩·图伯(Shawn Toubeau)

翻译自: /

twitter id生成类

更多推荐

twitter id生成类

本文发布于:2024-03-09 06:01:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1724088.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:twitter   id

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!