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