我正在创建一个简单的 Twitter 机器人,用于搜索相关主题标签并回复它们。我正在使用不记名令牌来搜索推文和消费者密钥来发布回复。 用户身份验证设置设置为“读取”和“写入”,并且我的所有密钥都是正确的。但是我在发送回复时收到 401 未经授权。我每月为基本计划支付 100 美元。
// Create object reference to libs
const Twitter = require('twitter-v2');
var fs = require('fs');
// Set Twitter API keys
var TWITTER_CONSUMER_KEY = '..';
var TWITTER_CONSUMER_SECRET = '..';
var TWITTER_ACCESS_TOKEN = '..';
var TWITTER_ACCESS_TOKEN_SECRET = '..';
var BEARER_TOKEN = '..';
// Database file
var DB_FILE = "bot_db.txt";
// Set interval time. Try to use a not so small interval to avoid Twitter to lock your account.
var INTERVAL = 3*60*60*1000; // 3 hours
// Set Twitter search phrase. You can use hash tags or simples text. Hash tags works better. Separate with OR or AND.
var TWITTER_SEARCH_PHRASE = '#Test1 OR #Otherhashtag';
// Set max number of tweets to get on the search results each time
var TWITTER_SEARCH_MAX_RESULTS = 20;
// Set tweets to reply
var TWEETS_TO_REPLY = [
"tweet text 1",
"tweet text 22",
];
var Bot = new Twitter({
consumer_key: TWITTER_CONSUMER_KEY,
consumer_secret: TWITTER_CONSUMER_SECRET,
access_token_key: TWITTER_ACCESS_TOKEN,
access_token_secret: TWITTER_ACCESS_TOKEN_SECRET
// bearer_token: BEARER_TOKEN
});
var Bot2 = new Twitter({
bearer_token: BEARER_TOKEN
})
async function BotStart() {
var myUserID = ..;
console.log("> Twitter bot is running (" + Date() + ")...")
const { data } = await Bot2.get('tweets/search/recent', {
query: TWITTER_SEARCH_PHRASE,
max_results: TWITTER_SEARCH_MAX_RESULTS
});
console.log(data);
// DB file
var bot_db = [];
// If db file doesn't exist, create empty file
if (!fs.existsSync(DB_FILE)) {
fs.closeSync(fs.openSync(DB_FILE, 'w'));
}
var fileData = await fs.readFileSync(DB_FILE, 'utf8');
fileData = fileData.trim();
if (fileData != "") {
bot_db = fileData.split("\n");
}
var processed_tweets = [];
for (var i = 0; i < data.length; i++) {
// Tweet id
var id = data[i].id;
// If id doesn't exist on database, process it
if (bot_db.indexOf(id) == -1) {
processed_tweets.push(id);
fs.appendFile(DB_FILE, id + "\n", function (err) {
if (err) {
console.log("Error on save to '" + DB_FILE + "' file.");
}
else {
console.log("tweet processed" + id);
}
});
// Reply
var textToReply = TWEETS_TO_REPLY[Math.floor(Math.random()*TWEETS_TO_REPLY.length)];
textToReply = "Hey " + textToReply;
try {
var replyData = await Bot.post('tweets', {text: textToReply, in_reply_to_tweet_id: id});
console.log("reply data " + textToReply);
} catch (error) {
console.log(error);
}
}
}
// Log of processed tweets
if (processed_tweets.length > 0) {
console.log("> Tweets processed: " + processed_tweets);
}
else {
console.log("> No tweets processed.");
}
}
// Start bot and timer
BotStart();
setInterval(BotStart, INTERVAL);
我多次尝试重新生成密钥,但不断遭到未经授权。
当我使用 twitter-api-v2 npm 包时它起作用了。也许是因为我可以使用该库设置读写: const rwClient1 = Bot.readWrite;