JavaScript로 첫 번째 Twitter 봇을 구축하는 쉬운 4단계
11063 단어 tutorialbotsbeginnersjavascript
NodeJS로 첫 번째 트윗을 만드는 방법에 대한 첫 번째 단계를 시작하겠습니다. 첫 번째 봇을 시작하고 실행하는 방법에 대한 간단한 4단계 프로세스를 살펴보겠습니다!
1단계: 액세스 권한 얻기
글을 쓰는 시점에서 개발자 Twitter 계정에 대한 요구 사항입니다. 그것은 훌륭하고 간단하며 작성하는 데 몇 분이 필요합니다.
이 단계는 아직 수행하지 않은 경우에만 필요합니다.
2단계: 토큰 받기
개발자 대시보드에 대한 액세스 권한이 있으면 첫 번째 앱을 만들고 .
대시보드에서
Projects & Apps > Your Project > Your App로 이동하여 상단의 탭에서 Keys and tokens를 선택해야 합니다. 이렇게 하면 API Key & Secret 를 복사하고 저장할 수 있습니다. 하루 정도만 사용할 수 있습니다. 안전한 곳에 보관하세요! 저는 항상 암호 관리자를 선택합니다.또한
Access Token & Secret 를 생성해야 합니다. 이것은 Authentication Tokens에서 수행됩니다. 이것을 복사하고 안전하게 보관하여 동일한 작업을 수행하십시오. 저장한 키 4개가 모두 필요합니다.
난독화된 인증 토큰 키
모든 작업을 완료한 후 키를 편리하게 보관하면 봇을 구축할 것입니다.
3단계: 읽기 + 쓰기 권한 추가
동일한 대시보드에서
Projects & Apps > Your Project > Your App로 이동하여 App permissions를 Read and Write로 변경해야 합니다.이는 위의 자격 증명으로 트윗할 수 있도록 하는 데 중요합니다.

읽기 + 쓰기 권한 선택
4단계: 애플리케이션 구축
지금은 짧고 간단하게 유지하여 첫 번째 트윗을 올릴 것입니다! 우리는 Twit 패키지를 게시하는 매체로 사용하고 Dotenv을 사용하여 로컬에서 런타임에 환경 변수를 로드할 것입니다(Git이 안전하게 무시할 수 있도록).
새 프로젝트의 루트에서:
# init with the basics
yarn init -y
yarn add twit
yarn add --dev dotenv
touch index.js .env .gitignore
.gitignore 내부에서 비밀이 원격 저장소에 저장되지 않도록 합시다.node_modules/
.env
이전에 저장한 액세스 토큰을 사용하여
.env에 추가해야 합니다.TWITTER_CONSUMER_KEY=<your-token>
TWITTER_CONSUMER_SECRET=<your-token>
TWITTER_ACCESS_TOKEN_KEY=<your-token>
TWITTER_ACCESS_TOKEN_SECRET=<your-token>
마지막으로
index.js에 코드를 추가해 보겠습니다.require("dotenv").config()
const Twit = require("twit")
const client = new Twit({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
})
/**
* Post a tweet to account.
*
* @example
* const tweet = await Twitter.post('This is an update', res.media.media_id_string);
* // returns success/error object
*
* @param {String} tweet Tweet string
* @param {Twitter} client Client instance of Twitter package
* @return {Promise<ClientResponse>} Return error or success object
*/
const post = tweet => {
const limit = 136
// ensure Tweet is correct length, but if not let's truncate
// and still post.
const tweetSubstr =
tweet.length > limit ? `${tweet.substring(0, limit - 3)}...` : tweet
const data = {
status: tweetSubstr,
}
// use the client to post the message
return client.post("statuses/update", data)
}
const main = async () => {
try {
console.log("Attempting to post")
await post("First post from the blog helper bot!")
console.log("Posted!")
} catch (err) {
console.error(err)
}
}
main()
index.js에서 수행하는 작업은 매우 간단하지만 분석해 보겠습니다..env 파일에서 env 변수를 필요로 하고 로드합니다Twit가 필요하고 환경 변수post 텍스트 게시를 시도하는 비동기 함수main "First post from the blog helper bot!" 함수 실행 It is worth noting that
postreturns a promise, hence why we makemainanasyncfunction and useawaitwhen calling to post
그게 다야! 이제
main를 실행해 보겠습니다. 성공하면 다음을 돌려받아야 합니다.> node index.js
Attempting to post
Posted!
If you are unsuccessful, there will be an error that is caught and logged out.
이제 Twitter로 이동하면 성공을 볼 수 있습니다!
첫 번째 트위터 봇 게시물
축하합니다! 이제 원격으로 게시하고 Twitterverse를 읽을 때 때때로 나타날 수 있는 모든 부정적인 분위기를 피할 수 있습니다!
리소스 및 추가 자료
이미지 크레디트: freestocks
원래 내 . 더 많은 숨겨진 보석을 보려면 Twitter에서 저를 팔로우하세요.
Reference
이 문제에 관하여(JavaScript로 첫 번째 Twitter 봇을 구축하는 쉬운 4단계), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/okeeffed/4-easy-steps-to-building-your-first-twitter-bot-with-javascript-1c93텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)