LoginSignup
ssmn93
@ssmn93

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ApiResponseError: Request failed with code 401

解決したいこと

discord.js v14とX API v2にて、discord側でスラッシュコマンドを実行すると特定のハッシュタグがついたtwitterの投稿を取得しdiscordでランダムに返すようにしたいので、そのうえで発生したエラーを解消したいです。

発生している問題・エラー

Error fetching tweets: ApiResponseError: Request failed with code 401
    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 IncomingMessage.emit (node:events:538:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  error: true,
  type: 'response',
  code: 401,
  headers: {
    perf: '7469935968',
    'content-type': 'application/problem+json',
    'cache-control': 'no-cache, no-store, max-age=0',
    'content-length': '99',
    'x-transaction-id': 'd8afd444d7c03df6',
    'x-response-time': '1',
    'x-connection-hash': '0a0dec5ffb6e1f05b8cd322b349588ceb48b298a421bfe5b890f3d169aff5dbc',
    date: 'Sat, 23 Mar 2024 16:08:52 GMT',
    server: 'tsa_b',
    connection: 'close'
  },
  rateLimit: undefined,
  data: {
    title: 'Unauthorized',
    type: 'about:blank',
    status: 401,
    detail: 'Unauthorized'
  }
}
[]
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 twitterClient = new TwitterApi({
  clientId: process.env.clientId,
  clientSecret: process.env.clientSecret,
  bearerToken: process.env.bearerToken,
});

const { EmbedBuilder } = require('discord.js');

async function getTweetsWithHashtag(hashtag) {
  try {
    const tweets = await twitterClient.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');
    }
  },
};

自分で試したこと

chatGPTやbingAI等を用いて、

const twitterClient = new TwitterApi({
clientId: process.env.clientId,
clientSecret: process.env.clientSecret,
bearerToken: process.env.bearerToken,
});

の部分の変更を試しました。

twitterのAPIに問題が生じていると考え、使用するアカウントを変更しました。

トークンのリセットを試しました。

developer portalの「App info」のURLを入れる箇所に適当にURLを入れてみましたが、入れなかったときと変わりませんでした。

twitterのAPIの権限
Screenshot 2024-03-23 18.37.55.png

追記

別サイトにおいても質問を行いました。
https://teratail.com/questions/dqc61u6a7o1huq
https://ja.stackoverflow.com/questions/98939/twitter-api%e3%81%ab%e3%81%8a%e3%81%91%e3%82%8bapiresponseerror-request-failed-with-code-401%e3%82%a8%e3%83%a9%e3%83%bc%e3%81%ae%e8%a7%a3%e6%b6%88

0

1Answer

This answer has been deleted for violation of our Terms of Service.

Your answer might help someone💌