Rediverse / eztwitch

Twitch API CLI and wrapper
https://npm.im/eztw
MIT License
6 stars 1 forks source link

Error on call any endpoint #3

Closed richardogcc closed 1 year ago

richardogcc commented 2 years ago

Client-ID and Authorization removed for obvious reasons.

On calling any endpoint ezTwitchClient.api('get', endpoints.CHANNEL_POINTS).then(console.log).catch(console.error) returns next error:

Error: Request failed with status code 404
    at createError (D:\Carpeta General\Trabajo\NodeJS\TwitchBots\NoctisMaiestatem\node_modules\axios\lib\core\createError.js:16:15)
    at settle (D:\Carpeta General\Trabajo\NodeJS\TwitchBots\NoctisMaiestatem\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (D:\Carpeta General\Trabajo\NodeJS\TwitchBots\NoctisMaiestatem\node_modules\axios\lib\adapters\http.js:293:11)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: 'Bearer xxxxxxxxxxxxxxxxxxxxxxx',
      'Client-ID': 'xxxxxxxxxxxxxxxxxxxxxxx',
      'User-Agent': 'axios/0.24.0'
    },
    method: 'get',
    url: 'https://api.twitch.tv[object Object]',
    data: undefined
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: false,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: 0,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'api.twitch.tv',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.twitch.tv',
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 180,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object],
      [Symbol(RequestTimeout)]: undefined
    },
    _header: 'GET /[object%20Object] HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxx\r\n' +
      'Client-ID: xxxxxxxxxxxxxxxxxxxxxxx\r\n' +
      'User-Agent: axios/0.24.0\r\n' +
      'Host: api.twitch.tv\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype],
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'GET',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/[object%20Object]',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 404,
      statusMessage: 'Not Found',
      client: [TLSSocket],
      _consuming: true,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://api.twitch.tv/[object%20Object]',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 22,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'api.twitch.tv',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://api.twitch.tv/[object%20Object]',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      authorization: [Array],
      'client-id': [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      connection: 'close',
      'content-length': '9',
      server: 'awselb/2.0',
      'content-type': 'text/plain; charset=utf-8',
      date: 'Tue, 14 Jun 2022 13:05:19 GMT',
      'x-served-by': 'cache-sea4449-SEA, cache-mad22043-MAD',
      'x-cache': 'MISS, MISS',
      'x-cache-hits': '0, 0',
      'x-timer': 'S1655211919.903374,VS0,VS0,VE165',
      vary: 'Accept-Encoding',
      'strict-transport-security': 'max-age=300'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'get',
      url: 'https://api.twitch.tv[object Object]',
      data: undefined
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'GET /[object%20Object] HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxx\r\n' +
        'Client-ID: xxxxxxxxxxxxxxxxxxxxxxx\r\n' +
        'User-Agent: axios/0.24.0\r\n' +
        'Host: api.twitch.tv\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/[object%20Object]',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.twitch.tv',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: 'Not Found'
  },
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

utils is working fine.

FishingHacks commented 2 years ago

endpoints.CHANNEL_POINTS is an object, that contains various endpoints that have something to do with Twitch Channel Points, such as endpoints.CHANNEL_POINTS.CREATE_CUSTOM_REWARD, and should not be used as an Endpoint.

(Sorry for my bad english)

RedCrafter07 commented 2 years ago

This is correct. Has it solved your issue?

richardogcc commented 2 years ago

How can I see the existing point rewards? I've tried with ezTwitchClient.api('get', endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION).then(console.log).catch(console.error); and also give me an error.

RedCrafter07 commented 2 years ago

Which error do you get?

richardogcc commented 2 years ago
data: {
      error: 'Bad Request',
      status: 400,
      message: 'Missing required parameter "broadcaster_id"'
    }
RedCrafter07 commented 2 years ago

EZTwitch doesn't take care of the needed params given by the Twitch API. Please check out the reference to see which parameters you need. In your case, to add the parameters, just do it like so:

ezTwitchClient.api('get', `${endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION}?your_param=xyz&other_param=abc`)

Replace your_param and other_param, as it's only a placeholder.

I hope I could help you :)

richardogcc commented 2 years ago

There's no way to get broadcaster id easily with EZTwitch?

RedCrafter07 commented 2 years ago

Not yet. Usually you just fetch the user using the login (reference). I use a chrome extension for that because it's faster, here's a link.

If you like, I'll add a feature like that to eztwitch soon.

richardogcc commented 2 years ago

I will give it a try, thanks!

RedCrafter07 commented 2 years ago

No problem, hope it helps! :)

FishingHacks commented 2 years ago

it should be

const broadcasterId = await ezTwitchClient.api('get', endpoints.USERS.GET.USER + "?name=<name>")
.then(data=>encodeURIComponent(data.user_id))
.catch(console.error);
await ezTwitchClient.api('get', endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION + "?broadcaster_id=" + broadcasterId).then(console.log).catch(console.error)
RedCrafter07 commented 2 years ago

it should be

const broadcasterId = await ezTwitchClient.api('get', endpoints.USERS.GET.USER + "?name=<name>").catch(console.error);
await ezTwitchClient.api('get', endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION + "?broadcaster_id=" + broadcasterId).then(console.log).catch(console.error)

Nope, you're putting the user data as a param here 🤔

FishingHacks commented 2 years ago

You could simplify it with a helper function:

async function getUserId(name, api) {
  return api.api('get', endpoints.USERS.GET.USER + "?name=" + encodeURIComponent(name)).then(user=>user.id).then(id=>encodeURIComponent(id));
}

await ezTwitchClient.api('get', endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION + "?broadcaster_id=" + await getUserId('channel_name'))
.then(console.log)
.catch(console.error)
RedCrafter07 commented 2 years ago

You don't need to encode the url component as the id is just a set of numbers without spaces etc.

FishingHacks commented 2 years ago

i know, just good practice

RedCrafter07 commented 2 years ago

Good point.

RedCrafter07 commented 2 years ago

@ArsDankeZik you might close this if we could help you :) Otherwise I'll close this in a week or so (I'll probably forget lol) if nothing happens to that moment. We're always happy to help and we hope you'll have fun using EzTwitch. If there's something to optimize, please tell us. Thanks ^^

RedCrafter07 commented 2 years ago

You could simplify it with a helper function:

async function getUserId(name, api) {
  return api.api('get', endpoints.USERS.GET.USER + "?name=" + encodeURIComponent(name)).then(user=>user.id).then(id=>encodeURIComponent(id));
}

await ezTwitchClient.api('get', endpoints.CHANNEL_POINTS.GET_CUSTOM_REWARD_REDEMPTION + "?broadcaster_id=" + await getUserId('channel_name'))
.then(console.log)
.catch(console.error)

@FishingHacks That works better than the solution you posted before that 👍

RedCrafter07 commented 1 year ago

I forgot it back then - I will close this now.