Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
Here's my code so far
--
`import openai
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from keep_alive import keep_alive
token = 'TOKEN'
openai.api_key = 'TOKEN_OPENAI'
bot = Bot(token)
dp = Dispatcher(bot)
#dp.message_handler()
async def send(message : types.Message):
response = openai.Completion.create(
model="text-davinci-003",
prompt=message.text,
temperature=0.9,
max_tokens=1000,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.6,
stop=["You:"]
)
await message.answer(response['choices'][0]['text'])
executor.start_polling(dp, skip_updates=True)
keep_alive()`
I already try using flask but still not working`
Related
This question already has answers here:
Discord.py - Make a bot react to its own message(s)
(2 answers)
Closed 2 years ago.
My code is like this, I want it to send a message and react to it, but after running it, nothing happens in the channel, and there's no error either.
#client.event
async def on_ready():
Channel = client.get_channel(775355712271941647)
Text = "React to get role"
moji = await Channel.send(Text)
await moji.add_reaction(emoji='🏃')
I found out the problem is I have two on_ready, and I should also use bot.event instead of client.event (because I named the client as bot).
So the following code would work if you have same problem as me:
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
moji = await bot.get_channel(775355712271941647).send("bot is online")
await moji.add_reaction(emoji='🏃')
import discord
import random
from discord.ext import commands, tasks
from itertools import cycle
from random import choice
client = commands.Bot(command_prefix = '.')
intents = discord.Intents.all()
#client.command()
#commands.guild_only()
async def ruser(ctx):
await ctx.send(choice(ctx.guild.members))
This is some code for a discord bot I'm working on. If you type ".ruser", it's supposed to send a message saying the user. The problem is that it is only returning the bots name, and not any of the users.
You didn't actually pass in the intents, you only declared the variable. You're supposed to add them to your bot as well.
intents = discord.Intents.all()
client = commands.Bot(command_prefix='.', intents=intents)
I am trying to create an event using Google Calendar API in Python 3. I also want to generate a Google Meet conference link for the event. I am using the documentations provided here:
https://developers.google.com/calendar/quickstart/python
https://developers.google.com/calendar/v3/reference/events#conferenceData
https://developers.google.com/calendar/create-events
The event is created without a problem. However, it is missing the conference link. My code so far is as follows:
from pathlib import Path
from pickle import load
from pickle import dump
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from uuid import uuid4
from typing import Dict, List
from oauth2client import file, client, tools
class EventPlanner:
def __init__(self, guests: Dict[str, str], schedule: Dict[str, str]):
guests = [{"email": email} for email in guests.values()]
service = self._authorize()
self.event_states = self._plan_event(guests, schedule, service)
#staticmethod
def _authorize():
scopes = ["https://www.googleapis.com/auth/calendar"]
credentials = None
token_file = Path("./calendar_creds/token.pickle")
if token_file.exists():
with open(token_file, "rb") as token:
credentials = load(token)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('calendar_creds/credentials.json', scopes)
credentials = flow.run_local_server(port=0)
with open(token_file, "wb") as token:
dump(credentials, token)
calendar_service = build("calendar", "v3", credentials=credentials)
return calendar_service
#staticmethod
def _plan_event(attendees: List[Dict[str, str]], event_time, service: build):
event = {"summary": "test meeting",
"start": {"dateTime": event_time["start"]},
"end": {"dateTime": event_time["end"]},
"attendees": attendees,
"conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
"conferenceSolutionKey": {"type": "hangoutsMeet"}}},
"reminders": {"useDefault": True}
}
event = service.events().insert(calendarId="primary", sendNotifications=True, body=event, conferenceDataVersion=1).execute()
return event
if __name__ == "__main__":
plan = EventPlanner({"test_guest": "test.guest#gmail.com"}, {"start": "2020-07-31T16:00:00",
"end": "2020-07-31T16:30:00"})
print(plan.event_states)
I suspect that the problem is with where I have passed conferenceDataVersion but the docs are not exactly clear about where it has to be passed other than that it must be passed. I also tried putting it in the body of the event or in createRequest. It always creates the event but not the conference. Unfortunately, I could not find anything about this online anywhere. Maybe I'm actually that bad at searching, but I have been testing different things and searching for a solution for several days! If anyone knows what I am missing, I will truly appreciate their assistance.
Thanks to #Tanaike, I found what was the problem. The token which is generated the first time the API is authenticated is very specific. The problem I was having turned out to be just with that. As soon as I removed the token and had it get generated again, the problem was solved. That being said, I have no idea why the problem appeared in the first place. I will update the response if I find the reason behind it. But for now, if you are having the same problem, just remove the token and regenerate it.
With this code we can create the conference (Google meet link) for me it works
"conferenceData": {
"createRequest": {
"requestId": "SecureRandom.uuid"
}
}
I'm attempting to make a Custom Search command using the Custom Search API.
Naturally I have no idea how to implement it. I'm hoping someone can take a look at what I have and help me figure out how to make it work in this style?
import discord
from discord.ext import commands
import discord.utils
import time
import os
import dotenv
from dotenv import load_dotenv
load_dotenv()
SEARCH = os.getenv("CUSTOM_SEARCH_API_KEY")
class Util(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command(name="Search", aliases=["search"])
#commands.has_permissions(embed_links=True, add_reactions=True)
async def _search(self, ctx, *, message):
if not ctx.author.Bot:
guild = ctx.guild
msg = ctx.message
cli = self.client.user
gold = discord.Color.dark_gold()
embed = discord.Embed(color=gold, name=f"{image.name}", description=f"{image.desc}", timestamp=msg.created_at)
embed.set_image(url=f"{image.url}")
embed.set_thumbnail(url=cli.avatar_url)
embed.set_footer(text=guild.name, icon_url=guild.icon_url)
await ctx.send(embed=embed)
return
def setup(client):
client.add_cog(Util(client))
I'm using dotenv to store my API key
Basically, I'm wanting it to be a somewhat detailed command.
If searching for posts it will find the exact post. and if searching for images it will go by tag and find a random image matching the selected tag(s).
I would like for it to respond via rich embed if possible.
I'm fully aware my above code won't work at all. I simply put it there as a base for part of the embed that I want to try to implement.
Some help would be much appreciated.
I'm using discord.py rewrite and I have my commands set up through cogs.
This is my bot.py file that contains the handler for my cogs.
import discord
from discord.ext import commands
import os
import json
import dotenv
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
PREFIX = os.getenv("COMMAND_PREFIX")
client = commands.Bot(command_prefix=PREFIX)
client.remove_command('help')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
client.run(TOKEN)
This question already has answers here:
Get the data received in a Flask request
(23 answers)
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Saving upload in Flask only saves to project root
(1 answer)
Closed 3 years ago.
I must upload file to flask via curl command. I tried sending using the curl commands from Folder/Files Upload with Flask and it failed to identify the request.
curl --form "fileupload=#filename.txt" http://hostname/resource
And the Python code:
from flask import Flask,abort,render_template,request,redirect,url_for
from werkzeug import secure_filename
import os
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route('/upload/',methods = ['POST'])
def upload_file():
if request.method =='POST':
file = request.files['file']
print request.files
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
if __name__ == '__main__':
app.run(debug = True)
The data should be saved upon POSTing via CURL command
Well you probably need to return something, without it Flask gives you error try to add
return jsonify({'message':'File uploaded!'})
after that and try it :) Remember to import jsonify from flask!