Twitter API를 사용하여 Twitter 봇을 만드는 방법
GitHub 파일:
나도 차근차근 만들어봤다video
내용 목록
First tweet
The Cron
트위터 앱 만들기
At First, we need to create a Twitter Application at the Twitter developer portal.
For that, you need to log in at .
In the left panel under Projects & Apps, click on Overview. Here, you can click on "Create App" to create a new application.
You have to give your application a name and confirm by clicking on next. On the next screen, you get the application's key and secrets displayed, which we won't be needing now.
We first have to make some other changes before we can use them properly. On the bottom right of your screen, click on app settings.
Here, we can change the authentication settings of our app.
Under "User authentication settings" click on "set up".
- Turn on both OAuth 1.0 & 2.0.
- As "Type of App" choose Automated App or Bot from the dropdown.
- App permissions set to "read and write"
The "Callback URI / Redirect URL" can't be set to localhost, so we need to paste in our local IP address. You can get it from your terminal
Windows
ipconfig
Linux/Mac
ifconfig
As Website URL, you can paste your personal website.
Hit save and we are ready to continue.
The Client ID and Client Secret which are displayed now are not needed in our case. Click on done to return to the dashboard.
Now we are ready to start coding.
Setup Project
Before we can start to create a node application, we have to make sure that node is installed.
Run node --version in your terminal. If you get a node version number printed, node is installed. If not, you need to go to the homepage and download the installer.
Once node is installed, we can create a new node application.
Create a new directory and switch into it.
mkdir twitter-bot && cd twitter-bot
Then run the following command to initialize a new npm project.
This will create a package.json inside the project directory.
npm init -y
In the next step we are going to add a npm module to our app which will help us to communicate with the Twitter API. This module is called twitter-api-v2 and can be found
To install it run the following command in your terminal
npm i twitter-api-v2
Once the installation is done, we can open up the project in our text-editor/IDEA.
트위터 클라이언트
Now we are going to create a twitter client. This client allows us to perform actions like tweets in our node application.
Create a new file, twitterClient.js.
Inside it, we need to require that Twitter API module and create our client by instantiate a new object of it. There we need to pass our keys, which we get from the .
On the overview page of your created application, select the "keys and tokens" tab.
Important: There you need to regenerate all tokens which we are going to use to make the auth settings take effect.
Copy and paste them into the twitter client, and export the client with readWrite permission.
You file should then look similar to this:
const {TwitterApi} = require("twitter-api-v2");
const client = new TwitterApi({
appKey: "<your-appKey>",
appSecret: "<your-appSecret>",
accessToken: "<your-accessToken>",
accessSecret: "<your-accessSecret>"
})
const rwClient = client.readWrite
module.exports = rwClient
첫 트윗
Now create a new file and name it index.js, here is where everything comes together.
At the top of the file, require the twitter client
const rwClient = require("./twitterClient.js");
Now we can create the function which will create a tweet from our Twitter profile. Notice: The function needs to be asynchronous. Then we can call and await the tweet method of our client. To the method pass any string which will then be our tweet.
The function could look like this:
const tweet = async () => {
try {
await rwClient.v1.tweet("Good Morning Friends!")
console.log("tweet successfully created")
} catch (e) {
console.error(e)
}
}
Then we need to call our function and test it.
tweet()
In your terminal run node index.js. If everything works properly, you should get the successfully created tweet message in your terminal prompted.
Check your Twitter profile!
왕관
In order to make this tweet to be created again after a certain time, we need to create a cronjob.
For that we are going to install another package called cron which you can find here .터미널에서
npm i cron
를 실행하여 설치하십시오.index.js
에 해당 모듈이 필요합니다.const CronJob = require("cron").CronJob;
마지막 단계: CronJob 클래스에서 새 작업을 만들고 특정 시간마다 실행하도록 합니다.
const job = new CronJob("0 5 * * *", () => {
console.log('cron job starting!')
tweet()
})
job.start();
설명: CronJob 클래스에서 새 개체를 만들고 두 개의 매개변수를 전달합니다. 첫 번째는 문자열이며 작업을 실행해야 할 때 선언합니다.
시간을 설정하는 훌륭한 도구는 CronTab Guru 입니다.
두 번째 매개변수는 호출하려는 콜백 함수입니다. 우리의 경우 작업이 시작될 때와 트윗 기능을 기록합니다.
그리고 그게 다야. node index.js를 실행하면 cron이 시작됩니다.
읽어 주셔서 감사합니다! 이 기사가 마음에 드셨으면 합니다. 피드백을 남겨주세요! :)
단계별 비디오
Reference
이 문제에 관하여(Twitter API를 사용하여 Twitter 봇을 만드는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dom_the_dev/how-to-use-the-twitter-api-to-create-a-twitter-bot-7l6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)