How to Build a Discord Bot That Posts Trending Topics
Build a Discord bot that posts live trending topics using TrendsAGI trends, Python code, scheduled digests, signed webhooks, and practical troubleshooting.

To build a Discord bot that posts trending topics, create a Discord app in the Developer Portal, follow Discord's Build Your First App guide for the bot skeleton, then add a trend source. This tutorial uses TrendsAGI as that source: fetch trends with its REST API or Python SDK, format them into Discord messages, and either poll on a schedule or push alerts through a signed TrendsAGI webhook to your bot's relay.
Discord's official developer platform supports building bots and integrations, and its docs cover the Developer Portal, API & SDK Reference, and Build Your First App guide. Use those for the Discord side. The code below covers the TrendsAGI side with exact endpoints and SDK calls; for message sending, use the documented Discord send method from your bot rather than guessing endpoints or limits.
What you are building
A trend-posting Discord bot has two jobs: get fresh trend data and deliver it to a channel. Keep those jobs separate. TrendsAGI handles trend detection, velocity, growth, AI insights, and alerting. Your Discord bot handles formatting and delivery according to Discord's documentation.
There are two practical patterns. A scheduled digest polls TrendsAGI every so often and posts the top trends as one message. An event alert uses a signed TrendsAGI webhook to notify a relay endpoint, which then asks your Discord bot to post. Scheduled digests are easier to reason about; webhook alerts are better when freshness matters.
Before you start
- Create a Discord app in the Developer Portal and follow Discord's Build Your First App guide. Use the API & SDK Reference for current app surfaces, permissions, scopes, and rate limits.
- Create a TrendsAGI API key in your account profile and store it in an environment variable. Do not hard-code it.
- Prepare a test Discord server and channel. Test there before posting to a community channel.
- Decide whether you need a scheduled digest, an event alert, or both. You can add the second pattern later.
Step 1: Create the Discord app and bot
Start in the Discord Developer Portal. Discord's documentation provides an Overview of Apps and a step-by-step Build Your First App guide for new developers. Follow that guide to register the app and add the bot to your test server. Discord's platform also supports rich presence, voice chat, and Activities, but a trend poster does not need those features.
The Discord side is intentionally not hard-coded here. Discord's API & SDK Reference is the authority for message payloads, permissions, and limits. Build the smallest bot that can send a plain text message to your test channel, then connect it to the trend code below.
Step 2: Connect TrendsAGI and fetch live trends
Install the Python SDK and set your API key from the environment:
export TRENDSAGI_API_KEY='your-key-here'
pip install trendsagi
The SDK includes both direct client methods and agent tools. This example uses tools.call because it returns a predictable dict and does not raise on tool failure.
import os
from trendsagi import TrendsAGIClient, TrendsAGITools
client = TrendsAGIClient(api_key=os.environ['TRENDSAGI_API_KEY'])
tools = TrendsAGITools(client)
result = tools.call('list_trends', {
'category': 'Technology',
'sort_by': 'velocity',
'limit': 5
})
if 'error' in result:
raise RuntimeError((result['error'], result.get('detail')))
trends = result['result']['trends']
for trend in trends:
print(trend['id'], trend['name'], trend['volume'], trend['category'])
You can also use the direct SDK method: client.get_trends(category='Technology', sort_by='velocity', limit=5). The REST equivalent is below.
curl -H 'X-API-Key: $TRENDSAGI_API_KEY' 'https://api.trendsagi.com/api/trends?category=Technology&sort_by=velocity&limit=5'
The /api/trends endpoint accepts query parameters including category, search, sort_by, sort_dir, limit, page, and period. Allowed sort_by values are velocity, growth, volume, timestamp, and name. Use GET /api/trends/categories when you want to discover categories before building your bot's filters.
Step 3: Add AI insights and analytics when you need context
A trend name alone is often enough for a digest. For richer posts, fetch AI insights and analytics for a specific trend ID.
trend_id = trends[0]['id']
insights = client.get_ai_insights(trend_id)
analytics = client.get_trend_analytics(trend_id, period='7d')
print(insights)
print(analytics)
REST equivalents:
curl -H 'X-API-Key: $TRENDSAGI_API_KEY' 'https://api.trendsagi.com/api/trends/$TREND_ID/ai-insights'
curl -H 'X-API-Key: $TRENDSAGI_API_KEY' 'https://api.trendsagi.com/api/trends/$TREND_ID/analytics?period=7d'
AI insights include a summary, key themes, sentiment, audience, and marketing angles. Analytics supports period=24h, 7d, or 30d. Velocity is a measured snapshot rate, not a forecast or unique-user count; present it that way in Discord so your community understands what the number means.
Step 4: Format the trend for Discord
Format trend data into a plain text message first. Plain text is easier to test and does not depend on Discord embed details. Once it works, map the same fields into the embed structure described in Discord's API & SDK Reference.
def format_trend(trend):
name = trend['name']
volume = trend['volume']
category = trend['category']
trend_id = trend['id']
return chr(10).join([
'Trending now: ' + name,
'Volume: ' + str(volume),
'Category: ' + category,
'Trend ID: ' + str(trend_id),
])
for trend in trends:
message = format_trend(trend)
print(message)
The final step is to pass message to your Discord bot's documented send method. If you want one digest instead of five separate posts, join the formatted messages with chr(10).join(...) and send one message. This is also the simplest way to reduce unnecessary posting frequency.
Step 5: Schedule posts or trigger alerts
For a daily or hourly digest, run the fetch-and-format code on a timer. Choose a cadence that matches your community's needs, and check Discord's API & SDK Reference for current limits rather than copying rate-limit numbers from random tutorials.
import time
POST_INTERVAL_SECONDS = 900
while True:
result = tools.call('list_trends', {
'category': 'Technology',
'sort_by': 'velocity',
'limit': 5
})
if 'error' not in result:
trends = result['result']['trends']
for trend in trends:
message = format_trend(trend)
# Send message with the Discord bot method from Discord's Build Your First App guide.
print(message)
time.sleep(POST_INTERVAL_SECONDS)
For event-driven alerts, create a signed TrendsAGI webhook that delivers to a relay endpoint. New subscriptions start paused. The response returns a one-time signing_secret; store it in your secret manager.
curl -X POST 'https://api.trendsagi.com/api/integrations/webhooks' -H 'X-API-Key: $TRENDSAGI_API_KEY' -H 'Content-Type: application/json' -d '{"url":"https://your-relay.example.com/trendsagi","trigger_type":"trend_category","delivery_mode":"instant_stream","threshold_value":500,"keywords":["Technology"],"cooldown_seconds":300}'
Send a test delivery, then activate the subscription:
curl -X POST -H 'X-API-Key: $TRENDSAGI_API_KEY' 'https://api.trendsagi.com/api/integrations/webhooks/$WEBHOOK_ID/test'
curl -X PATCH -H 'X-API-Key: $TRENDSAGI_API_KEY' -H 'Content-Type: application/json' -d '{"is_active":true}' 'https://api.trendsagi.com/api/integrations/webhooks/$WEBHOOK_ID'
Use GET /api/integrations/webhooks/{id}/executions to inspect delivery attempts. If a signing secret leaks, rotate it with POST /api/integrations/webhooks/{id}/rotate-secret.
Step 6: Receive and verify signed webhooks
Each TrendsAGI delivery includes the header X-Webhook-Signature. It is the lowercase hex HMAC-SHA256 of the exact raw request body, keyed with your signing secret. Verify it against the unmodified raw bytes with a constant-time comparison.
import hashlib
import hmac
import os
from flask import Flask, request, abort
app = Flask(__name__)
SIGNING_SECRET = os.environ['TRENDSAGI_WEBHOOK_SECRET'].encode()
@app.post('/trendsagi')
def trendsagi_webhook():
raw = request.get_data()
signature = request.headers.get('X-Webhook-Signature', '')
expected = hmac.new(SIGNING_SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
abort(401)
payload = request.get_json(force=True)
# Inspect the test delivery, then map fields to your Discord send method.
print(payload)
return {'ok': True}
Do not invent webhook body fields. Send a test delivery, inspect the JSON that arrives, and map those fields to your Discord message. If you use Slack instead of Discord, TrendsAGI supports Slack notifications; for Discord, keep the relay and bot send path.
Step 7: Add watchlists and recommendations
For a community manager, a watchlist turns the bot from a generic trend feed into a focused alert system. Create a topic interest with a volume threshold, then fetch recommendations for high-priority actions.
client.create_topic_interest(
keyword='AI chips',
alert_condition_type='volume_threshold',
volume_threshold_value=500
)
recommendations = client.get_recommendations(limit=10, priority='high')
print(recommendations)
REST equivalent:
curl -H 'X-API-Key: $TRENDSAGI_API_KEY' 'https://api.trendsagi.com/api/intelligence/recommendations'
Use GET /api/intelligence/crisis-events for crisis monitoring and GET /api/user/interests to review watchlists. Recommendation confidence measures evidence completeness, not probability of success, so phrase Discord alerts accordingly.
Bot, webhook, or command: which should you use?
| Approach | Best for | Trade-off |
|---|---|---|
| Bot app | Scheduled digests and server interaction | You own hosting, permissions, and monitoring; follow Discord's docs for limits and app setup. |
| Discord webhook | One-way delivery to a channel | Simpler delivery target, less interactive; confirm exact behavior in Discord's API & SDK Reference. |
| Command | <On-demand trend checks and community commands | Requires command registration and permission care; confirm current command behavior in Discord's API & SDK Reference. |
Practical use cases
Community daily digest. Post the top five trends by velocity into a community channel once or twice a day. Batch them into one message to keep the channel readable.
Marketing alert channel. Create a watchlist for a keyword with a volume threshold, then post high-priority recommendations when the threshold is crossed. Keep the wording factual: a threshold alert is not a forecast.
Indie niche bot. Use the search parameter or a narrow category to focus on one niche. This is easier to ship than a general trend bot because the output is more predictable.
Newsroom and PR monitoring. Combine high-growth trends with crisis events and route them to a private Discord channel. Use separate channels for routine trends and urgent alerts so the urgent channel stays useful.
Troubleshooting
- TrendsAGI returns 401. Check that
TRENDSAGI_API_KEYis set in the environment and that the request uses eitherX-API-KeyorAuthorization: Bearerexactly as documented. tools.callreturns an error object. It returns{'error': ..., 'detail': ...}instead of raising. Log both fields and stop that run rather than posting an empty digest.- The trend list is empty. Broaden the category or remove a narrow search. Use
GET /api/trends/categoriesor thelist_trend_categoriestool to confirm valid category names. - The webhook never fires. New subscriptions start paused. Send the test delivery with
POST /api/integrations/webhooks/{id}/test, then activate withPATCH /api/integrations/webhooks/{id}and{'is_active': true}. CheckGET /api/integrations/webhooks/{id}/executions. - Signature verification fails. Compute the HMAC over the exact raw request body. Do not parse JSON and re-encode it before hashing, and use a constant-time comparison.
- Duplicate Discord posts. Prevent overlapping timer runs until the previous run finishes. Keep a short record of trend IDs already posted and use
cooldown_secondson webhook subscriptions. - Discord delivery fails. Discord's API & SDK Reference is the authority for current permissions, scopes, and rate limits. This tutorial does not assume specific Discord limits.
Frequently asked questions
What is the fastest way to build a Discord bot that can post messages automatically?
Start with Discord's Build Your First App guide to get a bot that can send a plain message to a test channel. Then add a scheduled TrendsAGI fetch and post the formatted result; leave commands and embeds until the basic digest works.
How can a bot fetch trending topics and format them for a Discord channel?
Call GET /api/trends or client.get_trends(...), then use fields such as name, volume, category, and ID to build one text message. Add AI insights or analytics only when the extra context is useful to your community.
Which Discord app type, commands, or webhooks should I use for a trend-posting bot?
Use a bot app for scheduled posts and a documented command surface for on-demand checks. A Discord webhook can serve one-way delivery, but confirm its current behavior in Discord's API & SDK Reference before relying on it.
How do I schedule or trigger trend posts without hitting Discord API limits?
Poll on a fixed cadence, batch the top trends into a single message, and let one run finish before starting the next. For event alerts, use a TrendsAGI webhook with a cooldown and keep Discord's documented limits as the source of truth.
What are the trade-offs between using a bot, webhook, or slash command for trend alerts?
A bot is flexible but needs hosting and permission management; a webhook is simpler for one-way posts but less interactive; a slash command is useful when users request trends on demand. Start with a scheduled bot digest, then add the others only when needed.
How do I test and deploy the bot safely in a Discord server?
Use a separate test server and keep the API key and signing secret in environment variables or a secret manager. Log outgoing messages before enabling live posting, then monitor webhook executions and bot logs after deployment.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 3 December 2026 against the sources listed below.
We read the official Discord documentation listed below. The TrendsAGI steps and code use its documented REST API and Python SDK; confirm the Discord side against its current documentation, since third-party products change.
We re-research and rewrite this page at least every four months; the updated date only changes when the facts are re-checked.