StackOverflow.
I've been having a problem with a discord bot, here's the script:
def send():
url = "https://discordapp.com/api/webhooks/762125650546131005/lgYkjh-ILrag2sb3nzqUZfF1sg2mN2a0QeABaUq9dwl7qBTNL4EqWV00K62xWZ8_sNQ5"
data = {}
data["content"] = ""
data["username"] = "Suggestions"
data["embeds"] = []
embed = {}
embed["description"] = "**Author** » <#" + str(message.author.id) + ">\n **Suggestion** » " + str(args)
embed["title"] = "**New Suggestion!**"
data["embeds"].append(embed)
result = requests.post(url, data=json.dumps(data), headers={"Content-Type": "application/json"})
send()
await message.author.send("Thank you for your suggestion! We will look into it as soon as possible and will message you if it will be used.")
When I do ";suggestion fix bugs" it just sends to the webhook "fix" which is only the first word and I am struggling to fix this. Please may someone help?
Don't use requests with discord.py, it is sync and will block your bot, use a discord.Webhook with aiohttp to send a discord.Embed
Example:
from aiohttp import ClientSession
async with ClientSession() as session:
wh = discord.Webhook.from_url("<webhook url>", adapter=discord.AsyncWebhookAdapter(session))
e = discord.Embed()
e.title = "Hello I am an Embed"
...
await wh.send(embed=e)
Related
I am trying to build a Discord bot that takes the /create and generates images using the OpenAI DALL-E model, based on the user's input. However, after the bot prompts the message "What text would you like to generate an image for?", I input the text, but I get the error "Failed to generate image". What can I do? Thank you!
This is code that functions:
import os
import json
import requests
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command(name='create')
async def create_image(ctx):
await ctx.send("What text would you like to generate an image for?")
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
text = await bot.wait_for('message', check=check, timeout=60.0)
except asyncio.TimeoutError:
await ctx.send("Timed out, please try again.")
return
text = text.content
api_key = os.environ.get("API_KEY")
headers = {"Content-Type": "application/json"}
data = """
{
"""
data += f'"model": "image-alpha-001",'
data += f'"prompt": "{text}",'
data += """
"num_images":1,
"size":"1024x1024",
"response_format":"url"
}
"""
resp = requests.post(
"https://api.openai.com/v1/images/generations",
headers=headers,
data=data,
auth=("", api_key),
)
if resp.status_code != 200:
await ctx.send("Failed to generate image.")
return
response_text = json.loads(resp.text)
image_url = response_text['data'][0]['url']
await ctx.send(image_url)
bot.run('TOKEN')
Just like the title, I'm wanting to use the pexels api in a slash command to get random images from pexels (or any other site) using nextcord bot, hosting on repl.it. Begging for guidance, thank you in advance. See code below
async def init(interaction: Interaction):
await interaction.response.defer()
async with aiohttp.ClientSession()as session:
async with session.get(url = "https://api.pexels.com/v1/curated", headers = {'Authorization': "23456789"}, data = {"per_page": "1"}) as response:
raw = await response.text()
raw = raw.replace('[', '').replace(']', '')
init = json.loads(raw)
url = init["url"]
myobj = {'per_page':'1'}
embed = nextcord.Embed(page = init["page"], timestamp = datetime.now(), color = nextcord.Colour.green())
try:
embed.add_field(name = "Copyright", value = init["copyright"])
except KeyError:
pass
embed.set_image(url = url, myobj = myobj)
embed.set_footer(text = f"From {init['date']}")
await interaction.followup.send(embed = embed)
Im making a cripto price tracker and i cant make it reply the json that im making with the coin decko URL and Arg1 for example Eternal or SLP, etc.
# bot = scrt.bot
bot = commands.Bot(command_prefix = "!")
login = 0
tokens_dict = {
'morw' : '0x6b61b24504a6378e1a99d2aa2a5efcb1f5627a3a',
'slp' : '0xcc8fa225d80b9c7d42f96e9570156c65d6caaa25',
'pvu' : '0x31471e0791fcdbe82fbf4c44943255e923f1b794',
'eternal' : '0xd44fd09d74cd13838f137b590497595d6b3feea4'
}
# Login
#bot.event
async def on_ready():
global login
print('We have logged in as {0.user}'.format(bot))
login = 1
#bot.command()
async def coin(ctx, arg1):
global tokens_dict
if(arg1 in tokens_dict.keys()):
url = 'https://api.pancakeswap.info/api/v2/tokens/' + tokens_dict[arg1]
response = request.get(url)
responseDict = json.loads(response.text)
await ctx.reply(responseDict)
else:
await ctx.reply("The token " + str(arg1) + " is not in the token list, if you want to add " + str(arg1) + " to the list please use the command : " + '\n' + "!add_token")
In the coin function im trying to reply the json that ive created but i dont know how to.
response = request.get(url)
responseDict = json.loads(response.text)
await ctx.reply(responseDict)
I'm assuming this is the part you're talking about.
You actually don't need to call json.loads(response.text) if you're going to send it anyway. If the raw response is unformatted then you can do this
response_dict = json.loads(response.text)
formatted_dict = json.dumps(response_dict, indent=4)
await ctx.reply(formatted_dict)
This should send the json as a string with indents.
The reason discord.py wasn't letting you send the message was because it wasn't a string.
I am trying to extract the links from the hyperlinked texts, to be able to put them at the end of the message, and finally to remove the hyperlinks.
I tried to do it like this:
def extract_link(event):
event.message.message = event.message.message + "\nSources :"
for entity in event.message:
if isinstance(entity, MessageEntityTextUrl):
print(entity.url)
event.message.message = event.message.message + "\n- " + entity.url
event.message.entity = None
But i have this error :
Error: 'Message' object is not iterable
Use this code, this will help you!
from telethon import TelegramClient, sync, events
from telethon.tl.types import MessageEntityTextUrl
api_id =
api_hash = ''
client = TelegramClient('session', api_id, api_hash)
#client.on(events.NewMessage(chats=-1001675261848))
async def my_event_handler(event):
msg = event.message
for url_entity, inner_text in msg.get_entities_text(MessageEntityTextUrl):
url = url_entity.url
print(url)
client.start()
client.run_until_disconnected()
I have made youtube search command in discord.py but for some reason the bot only sends main page of youtube but not the term i want to search.
My code:
#bot.command()
#commands.cooldown(1, 60.00, commands.BucketType.guild)
async def yt(msg, *, search):
query_string = urllib.parse.urlencode({
"search_query": search
})
html_content = urllib.request.urlopen(
"http://www.youtube.com/results?" + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", html_content.read().decode())
await msg.send("http://www.youtube.com/watch?v" + search_results[0])
change this:
await msg.send("http://www.youtube.com/watch?v" + search_results[0])
to this:
await msg.send("http://www.youtube.com/watch?v=" + search_results[0])