質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Discord

Discordは、ゲーマー向けのボイスチャットアプリです。チャット・通話がブラウザ上で利用可能で、個人専用サーバーも開設できます。通話中でも音楽を流したり、PC画面を共有できるなど多機能な点が特徴です。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

Q&A

0回答

269閲覧

ApiResponseError: Request failed with code 401

ssmn_dev

総合スコア1

Discord

Discordは、ゲーマー向けのボイスチャットアプリです。チャット・通話がブラウザ上で利用可能で、個人専用サーバーも開設できます。通話中でも音楽を流したり、PC画面を共有できるなど多機能な点が特徴です。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Twitter

Twitterは、140文字以内の「ツイート」と呼ばれる短文を投稿できるサービスです。Twitter上のほぼ全ての機能に対応するAPIが存在し、その関連サービスが多く公開されています。

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

0グッド

1クリップ

投稿2024/03/23 09:40

編集2024/03/24 01:05

実現したいこと

discord.jsを用いて、discord上でスラッシュコマンドが実行されたら特定のハッシュタグを含むtwitterの投稿を取得し、ランダムに表示する。

発生している問題・分からないこと

const twitterClient = new TwitterApi({
にエラーが発生した。

エラーメッセージ

error

1ApiResponseError: Request failed with code 401 2 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) 3 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) 4 at IncomingMessage.emit (node:events:538:35) 5 at endReadableNT (node:internal/streams/readable:1345:12) 6 at processTicksAndRejections (node:internal/process/task_queues:83:21) { 7 error: true, 8 type: 'response', 9 code: 401, 10 headers: { 11 perf: '7469935968', 12 'content-type': 'application/problem+json', 13 'cache-control': 'no-cache, no-store, max-age=0', 14 'content-length': '99', 15 'x-transaction-id': '02da537da11f58e4', 16 'x-response-time': '1', 17 'x-connection-hash': '7359d0269c618fe0a967625e60ba3cc43e7723629a0db1bc485ac15543339495', 18 date: 'Sat, 23 Mar 2024 09:29:30 GMT', 19 server: 'tsa_b', 20 connection: 'close' 21 }, 22 rateLimit: undefined, 23 data: { 24 title: 'Unauthorized', 25 type: 'about:blank', 26 status: 401, 27 detail: 'Unauthorized' 28 } 29} 30[] 31No tweets found.

該当のソースコード

Javascript

1const fs = require('fs'); 2const path = require('path'); 3const { Intents } = require('discord.js'); 4const { SlashCommandBuilder } = require('@discordjs/builders'); 5const TwitterApi = require('twitter-api-v2').TwitterApi; 6require('dotenv').config({ path: '../.env' }); 7const Discord = require("discord.js"); 8 const { 9 Client, 10 GatewayIntentBits: { 11 Guilds, 12 GuildMessages, 13 MessageContent 14 }, 15 Collection, 16 Events, 17 GatewayIntentBits, 18 Partials, 19 Permissions 20 } = require("discord.js"); 21const client = new Discord.Client({ 22 'intents': [GatewayIntentBits.Guilds, 23 GatewayIntentBits.GuildMembers, 24 GatewayIntentBits.GuildEmojisAndStickers, 25 GatewayIntentBits.GuildIntegrations, 26 GatewayIntentBits.GuildVoiceStates, 27 GatewayIntentBits.GuildPresences, 28 GatewayIntentBits.GuildMessages, 29 GatewayIntentBits.GuildMessageReactions, 30 GatewayIntentBits.DirectMessages, 31 GatewayIntentBits.DirectMessageReactions, 32 GatewayIntentBits.MessageContent], 33 'partials': [Partials.User, 34 Partials.Channel, 35 Partials.GuildMember, 36 Partials.Message, 37 Partials.Reaction] 38}); 39 40const twitterClient = new TwitterApi({ 41 clientId: process.env.clientId, 42 clientSecret: process.env.clientSecret, 43 bearerToken: process.env.bearerToken, 44}); 45 46const { EmbedBuilder } = require('discord.js'); 47 48async function getTweetsWithHashtag(hashtag) { 49 try { 50 const tweets = await twitterClient.get(`https://api.twitter.com/2/tweets/search/recent?query=%23(ここにタグ名が入る)&max_results=10`); 51 console.log('Tweets:', tweets.data); 52 return tweets.data; // Twitter APIからのレスポンスを返す 53 } catch (error) { 54 console.error('Error fetching tweets:', error); 55 return []; // エラー時は空の配列を返す 56 } 57} 58 59module.exports = { 60 data: new SlashCommandBuilder() 61 .setName('search') 62 .setDescription('ツイート取得'), 63 64 async execute(interaction) { 65 try { 66 const tweets = await getTweetsWithHashtag('(タグ名)'); 67 console.log(tweets); 68 69 if (tweets.length > 0) { 70 // ツイートが取得できた場合の処理 71 const randomTweet = tweets[Math.floor(Math.random() * tweets.length)]; 72 console.log(randomTweet.text); 73 // ツイート情報を埋め込み形式で作成 74 const embed = new EmbedBuilder() 75 .setColor('#FFE201') 76 .setTitle('Random Tweet') 77 .setDescription(randomTweet.text) 78 .addField('Author ID', randomTweet.author_id) 79 .addField('Posted At', new Date(randomTweet.created_at).toUTCString()); 80 81 await interaction.reply({ embeds: [embed] }); 82 } else { 83 // ツイートが取得できなかった場合の処理 84 console.log('No tweets found.'); 85 await interaction.reply('No tweets found.'); 86 } 87 } catch (error) { 88 console.error('Error fetching tweets:', error); 89 await interaction.reply('Error fetching tweets'); 90 } 91 }, 92};

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

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を入れてみたが、入れなかったときと変わらなかった。

補足

権限

追記

別サイトにおいても質問をしました。
https://qiita.com/ssmn93/questions/1c08e39769cb499d85a5
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

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問