Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Giới Thiệu

Trong hướng dẫn từng bước này, tôi sẽ chia sẻ cách xây dựng một Bộ Lên Lịch Tweet sử dụng Upstash QStash, Upstash Redis, Next.js Server Actions và Vercel. Việc lên lịch đăng bài trên Twitter giúp bạn duy trì sự hiện diện đều đặn, tương tác với khán giả vào các khung giờ tối ưu, và quản lý chiến lược nội dung một cách hiệu quả.

Các Yêu Cầu Tiên Quyết

Bạn sẽ cần chuẩn bị:

  • Node.js 18 trở lên
  • Tài khoản Upstash
  • Tài khoản Twitter (X)
  • Tài khoản Vercel

Công Nghệ Sử Dụng

Công NghệMô Tả
UpstashNền tảng cơ sở dữ liệu serverless. Sử dụng Upstash Queue & QStash để lưu trữ tweet trong hàng đợi và gọi API lên lịch theo tần suất xác định.
Next.jsFramework React cho Web. Sử dụng shadcn/ui để tạo mẫu giao diện nhanh chóng.
TailwindCSSFramework CSS để xây dựng thiết kế tùy chỉnh.
VercelNền tảng đám mây để triển khai và mở rộng ứng dụng web.
PrettierCông cụ định dạng code theo quan điểm riêng để đảm bảo phong cách code nhất quán.

Các Bước Thực Hiện

Để hoàn thành hướng dẫn và triển khai bộ lên lịch tweet riêng, bạn cần thực hiện theo thứ tự:

  • Thiết lập Upstash Redis
  • Thiết lập Upstash QStash
  • Thiết lập Ứng Dụng Twitter Developer
  • Tạo ứng dụng Next.js mới
  • Triển khai Xác Thực Người Dùng với Twitter OAuth 2.0
  • Xây dựng Giao Diện Người Dùng để Lên Lịch Tweet
  • Lên Lịch Tweet bằng Upstash QStash
  • Triển khai lên Vercel

Thiết Lập Upstash Redis

Sau khi tạo tài khoản Upstash và đăng nhập, truy cập tab Redis và tạo một cơ sở dữ liệu mới.

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Sau khi tạo xong database, cuộn xuống phần REST API và chọn nút .env. Sao chép nội dung và lưu lại nơi an toàn.

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Thiết Lập Upstash QStash

Để lên lịch gửi yêu cầu POST đến endpoint lên lịch theo khoảng thời gian xác định, bạn sẽ sử dụng QStash. Truy cập tab QStash và cuộn xuống tab Request Builder.

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Sao chép QStash URL, TOKEN, Current Signing Key và Next Signing Key rồi lưu lại an toàn.

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Thiết Lập Ứng Dụng Twitter Developer

Để thiết lập xác thực với Twitter OAuth 2.0, bạn cần tạo một ứng dụng trên Twitter Developer Portal. Thực hiện theo các bước sau:

  • Mở Twitter Developer Portal > Projects.
  • Tạo một Project mới.
  • Vào tab Settings trong cài đặt ứng dụng:
    • Chọn Read and write and Direct message trong App permissions.
    • Chọn Web App, Automated App or Bot trong Type of App.
    • Nhập https://localhost:3000/api/auth/callback/twitter làm Callback URI / Redirect URL.
  • Vào tab Keys and tokens, cuộn xuống và thực hiện:
    • Sao chép Client ID lưu làm TWITTER_CLIENT_ID.
    • Sao chép Client Secret lưu làm TWITTER_CLIENT_SECRET.

Đến đây bạn đã thiết lập xong Ứng Dụng Twitter Developer cho OAuth 2.0.

Tạo Ứng Dụng Next.js Mới

Bắt đầu bằng cách tạo dự án Next.js mới. Mở terminal và chạy:

npx create-next-app@latest schedule-qstash-queue-upstash

Khi được hỏi, hãy chọn:

  • Yes cho TypeScript
  • No cho ESLint
  • Yes cho Tailwind CSS
  • No cho thư mục src/
  • Yes cho App Router
  • No cho tùy chỉnh import alias mặc định (@/*)

Di chuyển vào thư mục dự án và khởi chạy chế độ phát triển:

cd schedule-qstash-queue-upstash
npm run dev

Ứng dụng sẽ chạy tại localhost:3000.

Tạo file .env tại gốc dự án và thêm các biến môi trường từ các bước trước:

# .env
# Biến môi trường Twitter
TWITTER_CLIENT_ID="..."
TWITTER_CLIENT_SECRET="..."
TWITTER_AUTH_CALLBACK_URL="https://localhost:3000/api/auth/callback/twitter"

# Biến môi trường Upstash
UPSTASH_REDIS_REST_URL="https://...upstash.io"
UPSTASH_REDIS_REST_TOKEN="...="
QSTASH_URL="https://qstash.upstash.io/v2/publish/"
QSTASH_TOKEN="...="
QSTASH_CURRENT_SIGNING_KEY="sig_..."
QSTASH_NEXT_SIGNING_KEY="sig_..."

Tích Hợp Thành Phần shadcn/ui

Để nhanh chóng tạo mẫu giao diện, cài đặt shadcn/ui với Next.js:

npx shadcn-ui@latest init

Khi cấu hình components.json, chọn:

  • Yes cho TypeScript
  • Default cho style
  • Slate cho màu cơ bản
  • app/globals.css cho file CSS toàn cục
  • yes cho CSS variables
  • Để trống prefix Tailwind tùy chỉnh
  • tailwind.config.ts cho vị trí tailwind.config.js
  • @/components cho alias components
  • @/lib/utils cho alias utils
  • Yes cho React Server Components
  • Yes để ghi cấu hình vào components.json

Tiếp theo, cài đặt các thành phần UI cần thiết:

npx shadcn-ui@latest add button
npx shadcn-ui@latest add input
npx shadcn-ui@latest add textarea
npx shadcn-ui@latest add toast
npx shadcn-ui@latest add popover
npx shadcn-ui@latest add calendar

Bạn sẽ thấy thư mục ui trong app/components chứa các file component.

Cập nhật file app/layout.tsx để thêm Toaster:

// File: app/layout.tsx
import './globals.css'
import { cn } from '@/lib/utils'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import { Toaster } from '@/components/ui/toaster'

const fontSans = Inter({
  subsets: ['latin'],
  variable: '--font-sans',
})

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: Readonly<{ children: React.ReactNode }>) {
  return (
    <html lang="en">
      <body
        className={cn(fontSans.variable, 'min-w-screen flex min-h-screen flex-col items-center justify-center bg-background font-sans antialiased')}
      >
        {children}
        <Toaster />
      </body>
    </html>
  )
}

Tạo Hàng Đợi Upstash để Lưu Trữ Tweet Đã Lên Lịch

Trong phần này, bạn sẽ học cách sử dụng Upstash Queue để lưu trữ thông tin tweet đã lên lịch, và tạo code phía máy chủ được gọi như một hàm thay vì qua API route, sử dụng Next.js Server Actions.

Cài đặt các SDK Upstash cần thiết:

npm install @upstash/qstash @upstash/queue @upstash/redis@1.28.0

Các gói được cài đặt:

  • @upstash/qstash: SDK tương tác với QStash qua HTTP.
  • @upstash/queue: SDK quản lý hàng đợi dựa trên stream, backed by Upstash Redis.
  • @upstash/redis: SDK tương tác Redis qua HTTP, xây dựng trên Upstash REST API.

Khởi Tạo Client Upstash Redis và Upstash Queue

Tạo file lib/upstash.ts với nội dung sau:

// File: lib/upstash.ts
import { Redis } from '@upstash/redis'
import { Queue } from '@upstash/queue'

export const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL as string,
  token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
})

export const queue = new Queue({
  redis,
  queueName: 'tweets',
  concurrencyLimit: 5,
})

Code trên thực hiện:

  • Import class Redis và Queue từ các package.
  • Export instance redis trỏ đến Upstash Redis URL kèm token xác thực.
  • Export instance queue trỏ đến Redis đã tạo, đặt tên hàng đợi là tweets và concurrencyLimit = 5 (cho phép xử lý tối đa 5 tin nhắn đồng thời).

Sử dụng instance queue, tạo Next.js Server Action nhận nội dung tweet và ngày giờ để đẩy đối tượng tweet vào hàng đợi. Tạo file app/schedule.server.tsx:

// File: app/schedule.server.tsx
'use server'
import { queue } from '@/lib/upstash'
import type { FormProps } from './form'

export async function schedule(_: any, formData: FormData): Promise<FormProps> {
  try {
    const tweet_text = formData.get('tweet_text') as string
    const tweet_date = formData.get('tweet_date') as string
    const now = new Date().getTime()
    const delay = new Date(tweet_date).getTime() - now
    await queue.sendMessage({ tweet_text, tweet_date }, delay)
    return { ok: true, tweet_date }
  } catch (e) {
    console.log(e)
    return { ok: false }
  }
}

Code này:

  • Import instance queue
  • Export server action schedule nhận form chứa nội dung và ngày giờ tweet.
  • Tính toán độ trễ từ hiện tại đến thời điểm lên lịch.
  • Đẩy đối tượng tweet vào hàng đợi với độ trễ đã tính.

Cách này đảm bảo tweet chỉ được đẩy vào hàng đợi khi đến thời điểm lên lịch, giúp dễ dàng quản lý trạng thái hàng đợi — chỉ những tweet lên lịch trong ngày mới có trong hàng đợi.

Triển Khai Xác Thực Người Dùng với Twitter OAuth 2.0

Phần này hướng dẫn thiết lập luồng xác thực Twitter OAuth 2.0 trong ứng dụng bằng cách cấu hình OAuth client và sử dụng hàm hỗ trợ từ Twitter SDK. Luồng xác thực bao gồm tạo endpoint authorization và callback, cho phép người dùng cấp quyền và nhận token, sau đó lưu access token vào Upstash Redis. Cũng sẽ tạo endpoint kiểm tra trạng thái xác thực dựa trên sự hiện diện của access token hợp lệ trong Redis.

Cài đặt thư viện cần thiết:

npm install twitter-api-sdk

Tạo Twitter Authentication Client

Sử dụng auth client từ Twitter SDK để tạo URL xác thực mà không cần hiểu sâu cú pháp API Twitter. Tạo file lib/twitter.ts:

// File: lib/twitter.ts
import { auth } from 'twitter-api-sdk'

export const authClient = new auth.OAuth2User({
  client_id: process.env.TWITTER_CLIENT_ID as string,
  callback: process.env.TWITTER_AUTH_CALLBACK_URL as string,
  client_secret: process.env.TWITTER_CLIENT_SECRET as string,
  scopes: ['tweet.write', 'tweet.read', 'offline.access', 'users.read'],
})

Chuẩn Bị Twitter Authorization URL

Bước đầu trong luồng OAuth 2.0 là chuyển hướng người dùng đến authorization URL. Tạo file app/api/auth/twitter/route.ts:

// File: app/api/auth/twitter/route.ts
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { authClient } from '@/lib/twitter'

export async function GET() {
  const authUrl = authClient.generateAuthURL({
    state: 'state',
    code_challenge: 'challenge',
    code_challenge_method: 'plain',
  })
  return NextResponse.redirect(authUrl, 303)
}

Chuẩn Bị Authorization Callback URL

Bước thứ hai là xử lý callback từ Twitter. Tạo file app/api/auth/callback/twitter/route.ts:

// File: app/api/auth/callback/twitter/route.ts
export const dynamic = 'force-dynamic'
import { redis } from '@/lib/upstash'
import { NextResponse } from 'next/server'
import { authClient } from '@/lib/twitter'

export async function GET(request: Request) {
  const code = new URL(request.url).searchParams.get('code')
  if (!code) return NextResponse.json({}, { status: 403 })

  authClient.generateAuthURL({
    state: 'state',
    code_challenge: 'challenge',
    code_challenge_method: 'plain',
  })

  const { token: { access_token } } = await authClient.requestAccessToken(code)
  await redis.set('twitter_oauth_access_token', access_token)
  return NextResponse.redirect(new URL('/', request.url), 303)
}

Code này lưu access token vào Upstash Redis với key twitter_oauth_access_token.

Tạo endpoint kiểm tra trạng thái xác thực tại app/api/auth/twitter/authenticated/route.ts:

// File: app/api/auth/twitter/authenticated/route.ts
export const dynamic = 'force-dynamic'
import { redis } from '@/lib/upstash'
import { NextResponse } from 'next/server'

export async function GET() {
  try {
    const access_token = await redis.get<string>('twitter_oauth_access_token')
    if (!access_token) return NextResponse.json({ ok: false }, { status: 200 })
    return NextResponse.json({ ok: true }, { status: 200 })
  } catch(e) {}
  return NextResponse.json({ ok: false }, { status: 200 })
}

Xây Dựng Giao Diện Người Dùng Để Lên Lịch Tweet

Phần này tạo form reactive sử dụng React hooks useFormState và useFormStatus, gọi server action để lên lịch tweet.

Tạo file app/form.tsx cho component form:

// File: app/form.tsx
'use client'
import { cn } from '@/lib/utils'
import { format } from 'date-fns'
import { Button } from '@/components/ui/button'
import { Calendar } from '@/components/ui/calendar'
import { useToast } from '@/components/ui/use-toast'
import { Textarea } from '@/components/ui/textarea'
import { Calendar as CalendarIcon } from 'lucide-react'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { useFormStatus } from 'react-dom'
import { useEffect, useState } from 'react'

export interface FormProps {
  ok?: boolean
  tweet_date?: string
}

export default function ({ ok, tweet_date }: FormProps) {
  const { toast } = useToast()
  const { pending } = useFormStatus()

  useEffect(() => {
    if (!pending) {
      if (ok) {
        const scheduleForm = document.getElementById('schedule_form') as HTMLFormElement
        if (scheduleForm) scheduleForm.reset()
        toast({ title: 'Scheduled Tweet', description: tweet_date })
      } else {
        toast({
          variant: 'destructive',
          title: 'Uh oh! Something went wrong.',
          description: 'There was a problem with your request.',
        })
      }
    }
  }, [pending])

  const [date, setDate] = useState<Date>()

  return (
    <>
      <span className="font-semibold">Tweet Scheduler</span>
      <input id="tweet_date" name="tweet_date" className="hidden" value={date?.toString()} />
      <Popover>
        <PopoverTrigger asChild>
          <Button variant={'outline'} className={cn('w-[280px] justify-start text-left font-normal', !date && 'text-muted-foreground')}>
            <CalendarIcon className="mr-2 h-4 w-4" />
            {date ? format(date, 'PPP') : <span>Pick a date</span>}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0">
          <Calendar mode="single" selected={date} onSelect={setDate} />
        </PopoverContent>
      </Popover>
      <Textarea id="tweet_text" name="tweet_text" className="min-h-[300px] w-[280px]" placeholder="Tweet" />
      <Button disabled={pending} className="w-[280px]">
        {pending ? 'Scheduling...' : <>Schedule &rarr;</>}
      </Button>
    </>
  )
}

Tạo file components/twitter.tsx hiển thị trạng thái xác thực Twitter:

// File: components/twitter.tsx
'use client'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'

export default function () {
  const state = {
    pending: { message: '...', variant: 'outline' as const },
    true: { message: '✔️ Authenticated Instance', variant: 'secondary' as const },
    false: { message: '1-Time Authentication with Twitter →', variant: 'destructive' as const },
  }
  const [authenticated, setAuthenticated] = useState<string | boolean>('pending')

  useEffect(() => {
    fetch('/api/auth/twitter/authenticated')
      .then(res => res.json())
      .then(res => { setAuthenticated(res.ok as boolean) })
  }, [])

  return (
    <Button
      className="w-[280px]"
      onClick={() => { if (!authenticated) window.location.href = '/api/auth/twitter' }}
      variant={state[authenticated.toString()].variant}
    >
      {state[authenticated.toString()].message}
    </Button>
  )
}

Tạo file app/page.tsx để render form tại route index:

// File: app/page.tsx
'use client'
import Form from './form'
import { useFormState } from 'react-dom'
import Twitter from '@/components/twitter'
import { schedule } from './schedule.server'

export default function () {
  const [state, formAction] = useFormState(schedule, {})
  return (
    <div className="flex w-[300px] flex-col gap-y-3 p-5">
      <Twitter />
      <form id="schedule_form" action={formAction} className="flex w-[300px] flex-col gap-y-3">
        <Form {...state} />
      </form>
    </div>
  )
}

Lên Lịch Tweet Sử Dụng Upstash QStash

Tạo endpoint tiêu thụ dữ liệu tweet từ Upstash Queue và POST lên Twitter API. Tạo file app/api/schedule/route.ts:

// File: app/api/schedule/route.ts
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { queue, redis } from '@/lib/upstash'
import { verifySignatureAppRouter } from '@upstash/qstash/dist/nextjs'

interface TweetBody {
  tweet_text?: string
  tweet_date?: number
}

async function tweet(access_token: string, text: string | undefined) {
  if (text) {
    await fetch('https://api.twitter.com/2/tweets', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: ['Bearer', access_token].join(' '),
      },
      body: JSON.stringify({ text }),
    })
  }
}

async function handler() {
  const access_token = await redis.get<string>('twitter_oauth_access_token')
  if (!access_token) return NextResponse.json({}, { status: 403 })

  const tweets = await Promise.all(Array.from({ length: 4 }, () => queue.receiveMessage<TweetBody>()))
  await Promise.all(tweets.map(i => tweet(access_token, i?.body?.tweet_text)))
  return NextResponse.json({}, { status: 200 })
}

export const POST = verifySignatureAppRouter(handler)

Endpoint này:

  • Xác minh chữ ký yêu cầu để đảm bảo request từ QStash.
  • Lấy access token từ Redis.
  • Lấy 4 tin nhắn từ Queue và đăng tweet thay mặt người dùng.

Sử dụng QStash để tự động hóa: mỗi ngày nửa đêm, QStash sẽ POST đến /api/schedule. Trên Upstash Console, tab QStash > Request Builder:

  • Chọn tab Endpoint
  • Nhập URL tuyệt đối đến endpoint /api/schedule
  • Chọn Type = Scheduled
  • Chọn Every = every day at midnight
  • Nhấn Schedule

Xây dựng Bộ Lên Lịch Tweet với Upstash: Hướng Dẫn Chi Tiết Bước Đi Bước

Triển Khai Lên Vercel

Kho sẵn sàng để deploy Vercel:

  • Tạo repository GitHub chứa code ứng dụng.
  • Truy cập Vercel Dashboard, tạo New Project.
  • Liên kết với repository GitHub vừa tạo.
  • Trong Settings, cập nhật Environment Variables khớp với file .env local.
  • Nhấn Deploy.

Tham Khảo Thêm

  • GitHub Repository
  • Twitter OAuth 2.0 Flow
  • Generating Twitter App Tokens
  • React Form Hooks
  • Next.js Server Actions

Kết Luận

Trong hướng dẫn này, bạn đã học cách xây dựng một Bộ Lên Lịch Tweet mạnh mận tận dụng Upstash Redis và QStash. Khả năng mở rộng của Upstash đảm bảo lưu trữ và lên lịch tweet tin cậy, kết hợp với triển khai liền mạch trên Vercel tạo thành một hệ thống hoàn toàn tự động.