I have a music bot that streams radio and each stream is a command for ease of use. The problem is that there are 100+ stations now and it's getting increasingly more difficult to update the code for each one.
#bot.command(aliases=["VAR1", "VAR2"])
#commands.check(if_channel_private)
async def VAR(ctx):
current_time = datetime.now().strftime("%H:%M")
station = 'VAR3'
if len(embed_history.fields) <= 4:
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
elif len(embed_history.fields) > 4:
embed_history.remove_field(0)
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
stream = 'URL VAR4'
resume = stream
if len(pause_list) != 0 or len(radio_station) != 0:
pause_list.clear()
radio_station.clear()
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
try:
voice.play(FFmpegPCMAudio(stream))
print(f'Playing {station}')
except:
print(f"An error occurred while trying to play {station}")
await ctx.send(error_message)
radio_station.append(station)
pause_list.append(resume)
embed_st.clear_fields()
embed_st.add_field(inline=False, name=embed_name,
value="VAR5")
await ctx.send(embed=embed_st)
#VAR.error
async def _pr_error(ctx, error):
if isinstance(error, commands.CheckFailure):
if ctx.message.author.voice is None:
return
await ctx.send(f"Only users in __the same private voice channel__ can change the station!")
else:
await ctx.send(f"```css\n"
"[ERROR: Unexpected error has occured!]"
"```")
print(error)
This is how it looks like for each station. Is it possible to write this only once and then call it for every station? And only to have to change the variables (VAR)? Otherwise, it bloats the whole text file with repetitive code...
I don't check this code, but may be it's work. Create function, and send to it your variables station and stream:
#bot.command(aliases=["VAR", "VAR"])
#commands.check(if_channel_private)
async def VAR(ctx):
await some_function('VAR', 'URL_VAR')
# Your function for all stations
async def some_function(station, stream):
current_time = datetime.now().strftime("%H:%M")
if len(embed_history.fields) <= 4:
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
elif len(embed_history.fields) > 4:
embed_history.remove_field(0)
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
resume = stream
if len(pause_list) != 0 or len(radio_station) != 0:
pause_list.clear()
radio_station.clear()
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
try:
voice.play(FFmpegPCMAudio(stream))
print(f'Playing {station}')
except:
print(f"An error occurred while trying to play {station}")
await ctx.send(error_message)
radio_station.append(station)
pause_list.append(resume)
embed_st.clear_fields()
embed_st.add_field(inline=False, name=embed_name,
value="VAR")
await ctx.send(embed=embed_st)
Related
so i tried to make a spam function and run it but it just gives this error: RuntimeWarning: coroutine 'spam' was never awaited
spam(channel)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
and no message is being sent.
this is the code:
await guild.create_text_channel("NEEDLESS-NUKER")
for channel in guild.text_channels:
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
amount = 500
for i in range(amount):
await guild.create_text_channel(random.choice(SPAM_CHANNEL))
spam(channel)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.GREEN} Nuked {guild.name} Successfully.")
return
async def spam(channel):
for i in range(15):
try:
names = json.loads(open("words.json").read())
SPAM_MESSAGE = [
"#everyone LOL GET NUKED :skull::skull:",
"#everyone LOL IMAGINE GETTING NUKED :skull::skull:",
"lol hahaha get nuked",
f"im {random.choice(names)}",
f"Lol this is so random like {random.choice(names)}#{random.randint(1, 1000)} :skull:",
f"Made By {random.choice(names)}!",
]
msg = random.choice(SPAM_MESSAGE)
await channel.send(msg)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.GREEN} Succeffully send {msg}")
except Exception as e:
names = json.loads(open("words.json").read())
SPAM_MESSAGE = [
"#everyone LOL GET NUKED JOIN https://dsc.gg/pythondevs",
"#everyone LOL IMAGINE GETTING NUKED :skull::skull:",
"#everyone https://dsc.gg/pythondevs",
f"#everyone im {random.choice(names)}",
f"#everyone Lol this is so random like {random.choice(names)}!{random.randint(1000, 10000)}",
f"#everyone Made By {random.choice(names)}!",
]
msg = random.choice(SPAM_MESSAGE)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.RED} Failed Sending Message {msg} exc: {e}")
first it was #client.event and then on_guild_channel_create(channel) and it worked but now it wont work i changed it because everytime i created a channel with this bot it would send 15 messages in the channel and if i make a voice channel it just gives me an error.
so please help me fix this. Thanks.
You're calling an async function, so you need to create_task it or await it.
import asyncio
import time
async def wait:
time.sleep(1)
await asyncio.sleep(1)
return None
result = asyncio.create_task(wait()) #Wait 1 second.
await wait() #Wait 2 seconds because it will wait for execution to end.
In your case, you would need to change line 8 from (8th line of the answer)
spam(channel)
to
await spam(channel)
# https://bot.sannysoft.com/
from pyppeteer import *
from pyppeteer_stealth import stealth
import asyncio
# --------------------------------------------------------------
def handle_price(some_price):
for element in some_price:
try:
int(element)
except:
some_price = some_price.replace(element, '')
return some_price
#-----
async def get_wildberries_price(browser):
page = await browser.newPage()
await page.goto('https://www.wildberries.ru/catalog/98649739/detail.aspx')
await page.waitFor('.price-block__final-price')
raw_price = await page.evaluate('''
() => {
return document.querySelector('.price-block__final-price').textContent
}
''')
final_price = handle_price(raw_price)
await page.screenshot({'path': 'wildberries.png'})
return final_price
#-----
async def get_ozon_price(browser):
page = await browser.newPage()
await stealth(page)
await page.goto('https://www.ozon.ru/product/setka-sadovaya-plastikovaya-0-61-sm-opornaya-dlya-rasteniy-rulon-5-m-yacheyka-7-10-mm-zelenaya-746399567/?advert=LMWD3jhEugrU0NaiTNSLwpAIIbCdFMNn7pzKseZ54oiYJzffMkWL5dFUOvP2QxFxTe6r-62ds5iYdNtmm39GeVmWNx7Drk2RfA-NFruujb9wW_wbefQotjVI3Nw6nmw-7bz9eBuQf1jcWO9oKG03ATRZlVPYDWDUpt-Vr6TP01QKzNpkDGeyKNFDYr0mQ6zHtTc2xumWB3-dv2Gz-N1MubGGYv1HNBGFFtjS2sjma9sLgVekajUUaWojBH262l4QrAW1M9rCl-81e2UuCuA6e9e30jQi6V5VQGajDtoh7hlSqVBeuWTgQwBh93dIZprdLVVLO8wjhyroY4zH5kCXsPosmppupEfHuVI3WyxszZDRKZaftEvaKMKR1BDr1rtJDPW_pNvM1ZhWuCyJp9hsDQsED8fQ3RFRWR8LNZ5WYr8h_sjfYw1xlrl5-rjcS2MaBuBeYL3GQ4pXFwrkRKOEFuLsDScNPdIL2rDN9aeFT_lW5QnmTG_L177BU5QyZM2DLu7pN8H3K0To7QDSzvLpfVqCHWaudAT54N6mTU8GAtwBLp6sWpQNKDwnqqFLxmdC1s-3-U2t3h6jwkvEH5nue2hZdmrdu4Z-eD2qbnblV340tMRQZ3V8vcw-QO0BiDqNQupojM-i61GULUdv8a8qa12Uir-HZ1OOaKekgidc-IKoCUbTCa8YfpV5zXASOBlxvqs84FoG8vEg2yNkN4fRSOOkfcSp29rssttskpEkp14dZ3o_XnJ93SI1SR13ffRmFMGVZiwDjOyHjovEELGadA&avtc=1&avte=2&avts=1674570447&keywords=%D0%BF%D0%BB%D0%B0%D1%81%D1%82%D0%B8%D0%BA%D0%BE%D0%B2%D0%B0%D1%8F+%D1%81%D0%B5%D1%82%D0%BA%D0%B0+%D1%81%D0%BB%D0%B0%D0%B2&sh=6RhLQaLOhA')
await page.waitFor('[slot="content"] span')
raw_price = await page.evaluate('''
() => {
return document.querySelector('[slot="content"] span').textContent
}
''')
final_price = handle_price(raw_price)
await page.screenshot({'path': 'ozon.png'})
return final_price
# --------------------------------------------------------------
async def main():
main_browser = await launch({
# 'headless': False,
})
print(await get_wildberries_price(main_browser))
print(await get_ozon_price(main_browser))
await main_browser.close()
main_loop = asyncio.new_event_loop()
main_loop.run_until_complete(main())
Error: (Future exception was never retrieved
future:<Future finished exception=NetworkError('Protocol error Target.sendMessageToTarget: Target closed.')>
pyppeteer.errors.NetworkError: Protocol error Target.sendMessageToTarget: Target closed)
This error appears not often (about 1 time in a 4 starts).
But I noticed if I change places
print(await get_wildberries_price(main_browser))
print(await get_wildberries_price(main_browser))
code will be OK
I don't understand why place is important
I beg, help me, nothing works
Good day, I wrote a bot that responds to a user's request, but it happens that a message (also a file) intended for one user goes to another.
In the code I update the message and with this I show the download percentage of the sent video, but it happens that the message is updated from another chat, and the video goes to another user.
I'm not experienced enough in asynchronous programming.
from telethon import events, sync
from telethon.tl.types import PeerUser
from telethon.sync import TelegramClient
from decoder import *
from vodfinder import vod_list_create
import time, json
#git add . && git commit -m "g" && git push heroku master && heroku logs -t
class BotUser:
def __init__(self, mess_id, id):
self.id = id
self.user = PeerUser(user_id=self.id)
self.mess_id = mess_id
self.mess_text = ""
def upd_text(self, text):
self.mess_text = text
def step(self):
self.mess_id += 1
constants = json.load(open('constants.json'))
app = TelegramClient("TwitchTgBot",
api_hash=constants['api_hash'],
api_id=constants['api_id'])
ses_list = []
old_ses=""
#app.on(events.NewMessage(incoming=False))
async def messs_handler(message):
print(f"Outgoing: {message.id}")
async def downloader(filename, tsfile):
opener = urllib.request.build_opener()
tsfile.write(opener.open(filename).read())
#app.on(events.NewMessage(pattern='(/start)'))
async def start_handler(message):
session = BotUser(message.id + 3, message.chat.id)
ses_list.append(session)
await app.send_message(session.user,
f"Sup, its bot who can send you VODs from twitch, send me request!")
#app.on(events.NewMessage(incoming=True))
async def mess_handler(message):
print(f"Incoming : {message.id}")
if message.text[0] == "/":
return
raw_mess = message.text.split()
mess_id = message.id
chat = message.chat
for ses in ses_list:
if ses.id == chat.id:
session = ses
break
else:
await app.send_message(chat,
f"Bot doesn't start, send /start.")
return
async def upload_prg(current, total):
global old_ses
if old_ses != session:
print(f"Session changed to {session.id}")
old_ses = session
procent = f'{current * 100 / total:.1f}'
if session.mess_text != procent:
await app.edit_message(session.user, session.mess_id,
f"Uploading {procent} % ...")
session.upd_text(procent)
await asyncio.sleep(2)
async def download_prg(num, seg_range):
procent = f'{num * 100 / len(seg_range):.1f}'
if procent != session.mess_text:
await app.edit_message(session.user, session.mess_id,
f"Downloading {procent} % ...")
session.upd_text(procent)
await asyncio.sleep(2)
if len(raw_mess) == 5:
start_tm = int(raw_mess[2])
end_tm = int(raw_mess[3])
res_fps = raw_mess[4]
elif len(raw_mess) == 2:
start_tm = 0
end_tm = -1
res_fps = '720p60'
elif len(raw_mess) == 3:
start_tm = 0
end_tm = -1
res_fps = raw_mess[2]
else:
return
channel = raw_mess[0]
vod_cnt = int(raw_mess[1])
vod = vod_list_create(channel)[vod_cnt]
link = vod.vod_link.format(res_fps=res_fps)
print('A>>>>>>A\n')
print(f'User: {chat.username}')
print(f"Request: {message.text}")
print(vod.__str__())
print('Loading M3U8...')
end_tm, dump = dump_m3u8(link, end_tm)
print('M3U8 playlist loded.')
chunk_dur, parts = get_chunk_dur(res_fps, end_tm, start_tm)
print(f'Chunk duration is {chunk_dur}, splitted to {parts} part.')
await app.send_message(session.user,
f"Sending | {vod.__str__()} | splitted to {parts} parts...")
session.step()
last_seg = 0
for id_ in range(0, parts):
chunk_end = start_tm + chunk_dur
print(f'Decoding segments from {start_tm} to {chunk_end}.')
last_seg, seg_range = sec_to_seg(start_tm, chunk_end, last_seg, dump)
start_tm = chunk_end
await app.send_message(session.user,
f"Downloading {id_ + 1} part ...")
session.step()
print('Decoded, downloading ...')
tsfile = open(f'Downloaded/mg{id_}.mp4', 'ab')
for num, seg in enumerate(seg_range):
await downloader(link + str(seg)+ '.ts', tsfile)
await download_prg(num, seg_range)
tsfile.close()
print(f'Download of mg{id_}.ts finished.')
print(f'Sending mg{id_}.ts ...')
await app.send_file(session.user, f'Downloaded/mg{id_}.mp4', supports_streaming=True,
progress_callback=upload_prg)
await app.delete_messages(session.user, session.mess_id)
session.step()
print(f'mg{id_}.ts sended.')
print(f"[Sucsess] {chat.username}'s session finished.")
ses_list.remove(session)
app.start(bot_token=constants['token'] )
app.run_until_disconnected()
it accepts the request, downloads the video, sends it to the user
if I input !3people Job Offer I got this image's error. Please resolve my error.
My OS is windows 10 home and discord.py version is 1.0.1
Thank you.
if m.content.startswith('!') and 'Job Offer' in m.content:
if m.content\[1\].isdigit()!=True or int(m.content\[1\]) > 3 or int(m.content\[1\]) <= 0:
embed = discord.Embed(color=0x06afff)
embed = discord.Embed(title="Squad", color=0x06afff)
embed.add_field(name="warning", value="Please input correct value.", inline=False)
await m.channel.send(embed=embed)
else:
comment = ''
for i in m.guild.voice_channels:
if m.author in i.members:
embed = discord.Embed(title="Squad", color=0x06afff)
print(i.create_invite())
embed.add_field(name="Squad", value=(await i.create_invite()), inline=False)
print(i)
embed.add_field(name="Title", value=i, inline=False)
cnt=4-int(m.content\[1\])
embed.add_field(name="user count", value='%d /4'%(cnt), inline=False)
if 'Job Offer' in m.content:
comment = m.content.split('Job Offer')\[1\]
if len(comment) == 0:
comment = 'Today's finish is chicken'
embed.add_field(name="Comment", value=comment, inline=False)
await m.channel.send(embed=embed)
await m.channel.send('#here')
Error Image
create_invite is a coroutine so it needs to be awaited.
The simple fix is to edit line 12:
print(await i.create_invite())
Adding the await before i.create_invite() should solve the issue.
I've got a problem with discord.py bot, client.event on_message commands work perfectly for me but client.command() doesnt work, I've tried reinstalling everything from python to anaconda but it still doesnt work. (and sorry if question and code was messy I'm sort of new to programming and stackoverflow)
code:
import discord
import random
import time
from discord.ext import commands
import discord.utils
songs = []
songs_string = """HaB
LionNorth
Stalingrad
"""
i2 = 0
for song_name in songs_string.splitlines():
songs.insert(i2, song_name)
i2 += 1
list1 = []
help = '''
все команды должны начинаться с точки
dsw сюда ругательство,что бы добавить новое ругательство в sw на время сессии бота
time узнать текущее время
sabaton для получения случайной песни Сабатон (иногда может не работать из-за размера файла)
sw чтобы получить случайную ругань
'''
i = 0
string = f'''ПИДОРАС
ПОШЕЛ НАХУЙ
ДА ТЫ УЕБОК
не интересно,пидор
НАЧАЛЬНИК БЛЯТЬ,ЭТОТ ПИДОРАС ОБОСРАЛСЯ
бля ахуительная история
Я ТВОЙ НАЧАЛЬНИК
КТО БУДЕТ СОСАТЬ
ПОШЕЛ НА РАБОТУ
ЧИСТИ ГОВНО
НИХУЯ НЕ МОЖЕШЬ,ПОШЕЛ НАХУЙ
я с этим гондоном сидеть не буду бля
какие нахуй корабли?
'''
quotes_string = """Недостаточно овладеть премудростью, нужно также уметь пользоваться ею.
Тем, кто хочет учиться, часто вредит авторитет тех, кто учит.
Трудно быть хорошим..
"""
for word in string.splitlines():
list1.insert(i, word)
i += 1
restr = ["поговорим-по-душам", "🤓флудилка🤓", "⚠правила⚠", "🗯новости🗯"]
client = commands.Bot(command_prefix=".")
#client.command()
async def hi(ctx):
await ctx.send('Hi!')
#client.event
async def on_member_join(member):
for channel in member.guild.channels:
if str(channel) == "welcome":
await channel.send(f"""Welcome to the server {member.mention}""")
#client.event
async def on_message(message):
if str(message.channel) not in restr:
if message.content == ".sabaton":
random.seed(time.time())
randnum = random.randint(0, len(songs) - 1)
await message.channel.send(file=discord.File(songs[randnum]))
elif message.content == ".sw":
random.seed(time.time())
randnum = random.randint(0, len(list1) - 1)
await message.channel.send(list1[randnum].upper())
elif message.content == ".time":
await message.channel.send(f"Current time is {time.localtime()}")
elif message.content == ".help":
await message.channel.send(help)
if message.content.startswith(".dsw"):
msg = message.content.split()
output = ''
for word in msg[1:]:
output += word
output += ' '
await message.channel.send(f"{output} было добавлено в список ругательств на эту сессию")
list1.append(output)`
client.run("token here")
When using an on_message event, you'll need the bot to process_commands() if you're planning on using command decorators:
#client.event
async def on_message(message):
await client.process_commands(message)
# rest of your on_message code
References:
on_message
Bot.process_commands() - "Without this coroutine, none of the commands will be triggered. If you choose to override the on_message() event, then you should invoke this coroutine as well."