clients.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { Client, auth } from 'twitter-api-sdk'
  2. import { X_BOT_CLIENT_ID, X_BOT_CLIENT_SECRET } from '../../constants'
  3. import { Constant } from '../../db/models'
  4. // Initialize auth client first
  5. let authClient: auth.OAuth2User
  6. export async function getAuthClient(): Promise<auth.OAuth2User> {
  7. if (authClient) return authClient
  8. const token = await Constant.get('xBotToken')
  9. if (token) {
  10. authClient = new auth.OAuth2User({
  11. client_id: X_BOT_CLIENT_ID,
  12. client_secret: X_BOT_CLIENT_SECRET,
  13. callback: 'http://localhost:8089/api/v1/x/callback',
  14. scopes: ['tweet.read', 'users.read', 'offline.access'],
  15. token,
  16. })
  17. } else {
  18. authClient = new auth.OAuth2User({
  19. client_id: X_BOT_CLIENT_ID,
  20. client_secret: X_BOT_CLIENT_SECRET,
  21. callback: 'http://localhost:8089/api/v1/x/callback',
  22. scopes: ['tweet.read', 'users.read', 'offline.access'],
  23. })
  24. }
  25. return authClient
  26. }
  27. export async function getTwitterClient(): Promise<Client> {
  28. const authClient = await getAuthClient()
  29. return new Client(authClient)
  30. }