How to extract link from hyperlink in message with telethon? - python

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()

Related

"Failed to generate image" when using custom Discord bot that uses DALL-E to generate images

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')

Combining discord.py bot and python IRC client with asyncio

I have a discord bot written in python using the discord.py library and want to combine it with a basic selfwritten IRC client. My idea was to use the discord bot to control the IRC client (join and part channels) and run them both simultaneously.
discordbot.py:
import time
import configparser
import datetime as dt
import os
from typing import (
Any,
Optional,
Dict,
List
)
import discord
from discord.ext import commands
from irc import IRCSimpleClient
root_path = os.path.dirname(__file__)
config = configparser.ConfigParser()
config.read("config.cfg")
class Main(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.all()
super().__init__(command_prefix=commands.when_mentioned_or('!'),
intents=intents)
async def on_ready(self):
pass
def watch_message():
while True:
msg = irc.get_response()
msg = ""
if "PING" in msg:
irc.respond_ping(msg)
print(dt.datetime.strftime(dt.datetime.now(), "%H:%M") + " PONG")
try:
msg = msg.strip().split(":")
print("[{}][{}]<{}> {}".format(
dt.datetime.strftime(dt.datetime.now(), "%H:%M"),
"#" + msg[1].split(" #")[1].strip(),
msg[1].split("!")[0],
msg[2].strip()))
except IndexError:
pass
bot = Main()
#bot.command(name="join")
async def test(ctx: commands.Context):
irc.join_channel("test")
username = config["Auth"]["username"]
oauth = config["Auth"]["oauth"]
irc = IRCSimpleClient(username, oauth)
irc.connect()
irc.join_channel("lcs")
# watch_message()
token = config["discord"]["token"]
bot.run(token)
irc.py:
#!/usr/bin/env python
import socket
import time
class IRCSimpleClient():
def __init__(self, nick, oauth):
self.username = nick
self.oauth = oauth
self.server = "irc.chat.twitch.tv"
self.port = 80
def connect(self):
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.connect((self.server, self.port))
self.conn.send(f"PASS oauth:{self.oauth}\r\n".encode("utf-8"))
self.conn.send(f"NICK {self.username}\r\n".encode("utf-8"))
while not self.is_connected:
resp = self.get_response()
print(resp.strip())
if "376" in resp:
self.is_connected = True
if "PING" in resp:
self.respond_ping(resp)
def get_response(self):
return self.conn.recv(1024).decode("utf-8", "ignore")
def send_cmd(self, cmd, message):
command = "{} {}\r\n".format(cmd, message).encode("utf-8")
self.conn.send(command)
def send_message_to_channel(self, channel, message):
command = "PRIVMSG {}".format(channel)
message = ":" + message
self.send_cmd(command, message)
def join_channel(self, channel: str):
joined = False
cmd = "JOIN"
if not channel.startswith("#"):
channel = "#" + channel
self.send_cmd(cmd, channel)
while not joined:
resp = self.get_response()
print(resp.strip())
if "366" in resp:
joined = True
if "PING" in resp:
self.respond_ping(resp)
def part_channel(self, channel: str):
cmd = "PART"
if not channel.startswith("#"):
channel = "#" + channel
self.send_cmd(cmd, channel)
def respond_ping(self, message):
self.send_cmd("PONG", ":" + message.split(":")[1])
As far as I know, discord.py uses asyncio under the hood so I wanted to use it as well but since the IRC client is blocking when waiting to receive new messages, I'm not sure how to run both at the same time.
I tried asyncio and threading but the "watch_message" function is always blocking the discord bot run function from executing.

Nextcord Discord Bot, Use API with Pexels API to get random images

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)

member is a required arg that is missing

I have a problem with my bot because I don't want to load certain variables that are specified. If you see any errors in the code, I'd be very grateful if you could help.
Error: discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Here is code:
#!/usr/bin/python
import os
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('')
bot = commands.Bot(command_prefix = "/")
client = commands.Bot(command_prefix = "/")
#bot.event
async def on_ready():
print("----------------------")
print("Zalogowano jako:")
print("Użytkownik: %s"%client.user.name)
print("ID: %s"%client.user.id)
print("----------------------")
#bot.command(name='tutorial', help='Tutorial')
async def tutorial(ctx, member: discord.Member):
message = await ctx.send('flag_gb In which language do you want to receive the instructions?')
message = await ctx.send('flag_gb W jakim języku chcesz otrzymać instrukcje?')
flag_pl = 'flag_pl'
flag_gb = 'flag_gb'
await message.add_reaction(flag_pl)
await message.add_reaction(flag_gb)
def check(reaction, user):
return user == ctx.author and str(
reaction.emoji) in [flag_pl, flag_gb]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=10.0, check=check)
if str(reaction.emoji) == flag_pl:
em = discord.Embed(tittle = "flag_pl", description = "**1**")
em.add_field(name = "Opcja 1", value = "Link" );
await member.send(embed=em)
if str(reaction.emoji) == flag_gb:
em = discord.Embed(tittle = "flag_gb", description = "**2**")
em.add_field(name = "Opcja 2", value = "Link" );
await member.send(embed=em)
except:
print("Wystapil blad!")
bot.run('TOKEN')
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing means that you have to put the name of the member after the command (e.g. /tutorial user123 instead of /tutorial #user123). Also, an error you made is in
flag_pl = 'flag_pl'
and
flag_gb = 'flag_gb'
The emojis in discord always begin and end with :, so it should be
flag_gb = ':flag_gb:'
and
flag_pl = ':flag_pl:'

Problem with importing discord.py modules

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)

Categories