解決したいこと
discord.js v14とX API v2にて、discord側でスラッシュコマンドを実行すると特定のハッシュタグがついたtwitterの投稿を取得しdiscordでランダムに返すようにしたく、そのうえで発生したエラーを解消したいです。
(なおError fetching tweetsと[]とNo tweets found.はプログラム側で追加されたものになります。)
エラーログ
Error fetching tweets: ApiResponseError: Request failed with code 403
at RequestHandlerHelper.createResponseError (/rbd/pnpm-volume/d9af4806-06c4-4055-abaa-95683c0ef89c/node_modules/twitter-api-v2/dist/cjs/client-mixins/request-handler.helper.js:104:16)
at RequestHandlerHelper.onResponseEndHandler (/rbd/pnpm-volume/d9af4806-06c4-4055-abaa-95683c0ef89c/node_modules/twitter-api-v2/dist/cjs/client-mixins/request-handler.helper.js:262:25)
at Gunzip.emit (node:events:526:28)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
error: true,
type: 'response',
code: 403,
headers: {
date: 'Sun, 24 Mar 2024 04:22:10 UTC',
perf: '7469935968',
server: 'tsa_b',
'set-cookie': [
'guest_id=v1%3A171125413004808473; Max-Age=34214400; Expires=Thu, 24 Apr 2025 04:22:10 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None'
],
'api-version': '2.95',
'content-type': 'application/json; charset=utf-8',
'cache-control': 'no-cache, no-store, max-age=0',
'content-length': '328',
'x-access-level': 'read',
'x-frame-options': 'SAMEORIGIN',
'content-encoding': 'gzip',
'x-transaction-id': '31ed000a8d001098',
'x-xss-protection': '0',
'x-rate-limit-limit': '40000',
'x-rate-limit-reset': '1711254949',
'content-disposition': 'attachment; filename=json.json',
'x-content-type-options': 'nosniff',
'x-rate-limit-remaining': '39998',
'strict-transport-security': 'max-age=631138519',
'x-response-time': '13',
'x-connection-hash': '27dc75c45ab2f6430c55e036d053de80dd26706b33e085d311414c8dd1154438',
connection: 'close'
},
rateLimit: { limit: 40000, remaining: 39998, reset: 1711254949 },
data: {
client_id: '27837829',
detail: 'When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.',
registration_url: 'https://developer.twitter.com/en/docs/projects/overview',
title: 'Client Forbidden',
required_enrollment: 'Appropriate Level of API Access',
reason: 'client-not-enrolled',
type: 'https://api.twitter.com/2/problems/client-forbidden'
}
}
[]
No tweets found.
ソースコード
const fs = require('fs');
const path = require('path');
const { Intents } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const TwitterApi = require('twitter-api-v2').TwitterApi;
require('dotenv').config({ path: '../.env' });
const Discord = require("discord.js");
const {
Client,
GatewayIntentBits: {
Guilds,
GuildMessages,
MessageContent
},
Collection,
Events,
GatewayIntentBits,
Partials,
Permissions
} = require("discord.js");
const client = new Discord.Client({
'intents': [GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.MessageContent],
'partials': [Partials.User,
Partials.Channel,
Partials.GuildMember,
Partials.Message,
Partials.Reaction]
});
const appOnlyClient = new TwitterApi(process.env.bearerToken);
const v2Client = client.v2;
const { EmbedBuilder } = require('discord.js');
async function getTweetsWithHashtag(hashtag) {
try {
const tweets = await appOnlyClient.get(`https://api.twitter.com/2/tweets/search/recent?query=%23(タグ名)&max_results=10`);
console.log('Tweets:', tweets.data);
return tweets.data; // Twitter APIからのレスポンスを返す
} catch (error) {
console.error('Error fetching tweets:', error);
return []; // エラー時は空の配列を返す
}
}
module.exports = {
data: new SlashCommandBuilder()
.setName('search')
.setDescription('ツイート取得'),
async execute(interaction) {
try {
const tweets = await getTweetsWithHashtag('#(タグ名)');
console.log(tweets);
if (tweets.length > 0) {
// ツイートが取得できた場合の処理
const randomTweet = tweets[Math.floor(Math.random() * tweets.length)];
console.log(randomTweet.text);
// ツイート情報を埋め込み形式で作成
const embed = new EmbedBuilder()
.setColor('#FFE201')
.setTitle('Random Tweet')
.setDescription(randomTweet.text)
.addField('Author ID', randomTweet.author_id)
.addField('Posted At', new Date(randomTweet.created_at).toUTCString());
await interaction.reply({ embeds: [embed] });
} else {
// ツイートが取得できなかった場合の処理
console.log('No tweets found.');
await interaction.reply('No tweets found.');
}
} catch (error) {
console.error('Error fetching tweets:', error);
await interaction.reply('Error fetching tweets');
}
},
};
試したこと
もともと「ApiResponseError: Request failed with code 401」エラーが発生したため質問し、いただいた回答を元に自分なりに変更したところ403エラーが発生しました。
以前行った質問
https://teratail.com/questions/dqc61u6a7o1huq
https://qiita.com/ssmn93/questions/1c08e39769cb499d85a5
Twitter APIにおけるApiResponseError: Request failed with code 401エラーの解消
別サイトでの質問
https://teratail.com/questions/d3p0annjiez5tm
https://qiita.com/ssmn93/questions/8488a912e8b88a4b1e00
なおAPIはfreeプラン(無料版)です。