1+ # The required libraries
2+
3+ import discord
4+ import schedule
5+ import asyncio
6+ import requests
7+ import openai
8+
9+ openai .api_key = 'YOUR_OPENAI_API_KEY'
10+ # Get a key at https://platform.openai.com/docs/api-reference
11+
12+
13+
14+ CLIENT_TOKEN = 'YOUR_DISCORD_TOKEN'
15+ # Get a token at the discord developer portal https://discord.com/developers/docs/intro
16+
17+ CHANNEL_ID = "CHANNEL_ID"
18+ # The channel ID, AKA the channel in which the bot will send news articles in
19+
20+ url = "https://newsapi.org/v2/top-headlines"
21+ params = {
22+ "country" : "us" ,
23+ "apiKey" : "YOUR_NEWS_API_KEY"
24+ # Generate your API key from https://newsapi.org
25+ }
26+
27+
28+
29+ intents = discord .Intents .default ()
30+ intents .members = True
31+
32+ client = discord .Client (intents = intents )
33+
34+ latest_url = ""
35+
36+
37+
38+
39+ def get_latest_article ():
40+ global latest_article
41+ response = requests .get (url , params = params )
42+ articles = response .json ()['articles' ]
43+ latest_article = articles [0 ]
44+ return latest_article
45+
46+
47+ async def send_article ():
48+ global latest_url
49+ latest_article = get_latest_article ()
50+ if latest_article ['url' ] != latest_url :
51+ channel = await client .fetch_channel (CHANNEL_ID )
52+ message = f"New article: { latest_article ['title' ]} - { latest_article ['url' ]} "
53+ await channel .send (message )
54+ latest_url = latest_article ['url' ]
55+ response_text = f'\n { message } '
56+
57+ # Feel free to add your own prompts
58+ prompt = "Come up with a sarcastic response to this news article " + response_text
59+ response = openai .Completion .create (
60+ model = "text-davinci-003" ,
61+ prompt = prompt ,
62+ temperature = 0.7 ,
63+ max_tokens = 60 ,
64+ top_p = 1 ,
65+ frequency_penalty = 0 ,
66+ presence_penalty = 0
67+ )
68+ sarcastic_response = response .choices [0 ].text .strip ()
69+ if sarcastic_response :
70+ await channel .send (sarcastic_response )
71+ else :
72+ return 'no update found'
73+
74+
75+ @client .event
76+ async def on_ready ():
77+ print ('Bot is ready.' )
78+ schedule .every (10 ).minutes .do (send_article )
79+
80+ while True :
81+ await send_article ()
82+ await asyncio .sleep (10 * 60 ) # wait for 10 minutes before sending the next article to avoid using to many resources
83+
84+
85+
86+
87+ client .run (CLIENT_TOKEN )
0 commit comments