I'm trying to make a queue command but these two parts wont work {0.source.title} and {0.source.url} keep giving me this error
embed = (discord.Embed(description=f'**Music Queue ({len(ctx.voice_state.songs)} track)**\n**Now Playing:**\n[{0.source.title}]({0.source.url}) {self.source.duration_left} Left\n{queue}', color = discord.Colour.dark_red())
Error:
Unexpected token at end of expression Pylance [427, 144]
Here is the full code:
#commands.command(name='queue')
async def _queue(self, ctx: commands.Context, *, page: int = 1):
"""Shows the player's queue.
You can optionally specify the page to show. Each page contains 10 elements.
"""
source = self.source
if len(ctx.voice_state.songs) == 0:
return await ctx.send('Empty queue.')
items_per_page = 10
pages = math.ceil(len(ctx.voice_state.songs) / items_per_page)
start = (page - 1) * items_per_page
end = start + items_per_page
queue = ''
for i, song in enumerate(ctx.voice_state.songs[start:end], start=start):
queue += '`{0}` [**{1.source.title}**]({1.source.url})\n'.format(i + 1, song)
if queue == 1:
embed = (discord.Embed(description=f'**Music queue ({{len(ctx.voice_state.songs)}} track)**\n**Now Playing:**\n[{0.source.title}]({0.source.url}) {self.source.duration_left} Left\n{queue}', color = discord.Colour.dark_red())
.set_footer(text='Viewing page {}/{}'.format(page, pages)))
await ctx.send(embed=embed)
else:
embed = (discord.Embed(description=f'**Music Queue ({len(ctx.voice_state.songs)} tracks)**\n**Now Playing:**\n[{0.source.title}]({0.source.url}) {self.source.duration_left} Left\n{queue}', color = discord.Colour.dark_red())
.set_footer(text='Viewing page {}/{}'.format(page, pages)))
await ctx.send(embed=embed)
Related
I'm trying to count the entire embed list but it always shows me the same number...
should appear
1
2
3
4
...
I don't know how to solve this problem
this is the code
#bot.command()
async def habbo(ctx):
response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json")
data = response.json()
count=0
for i in data:
count=count+1
content = f'\n\n{contar} - '.join(item['name'] for item in data)
embed = discord.Embed(title=f"", description=f"{content}", color=discord.Colour.random())
await ctx.send(embed=embed)
This should work. I just removed the .join() function and created the appending with a loop instead.
#bot.command()
async def habbo(ctx):
response = requests.get("https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json")
data = response.json()
count = 0
content = ""
for item in data:
count = count + 1
item = item["name"]
content = content + f"\n{count} - {item}\n"
embed = discord.Embed(title=f"", description=f"{content}", color=discord.Colour.random())
await ctx.send(embed=embed)
I have a working script but when I changed the page.on in playwright it actually runs the network response a certain number of times as per the loop count. I have been trying to figure out why that happens.
For example at i=0 it gives one response.url print but at i=10 it prints response.url 10 times and then send 10 duplicate data to mongodb. I have no idea why this is happening. The link being sent based on the print are all the same.
Would be a great help if anyone can let me know what it is that I am doing wrong that is causing this issue.
Pls see sample code here.
#imports here
today = datetime.today().strftime("%m%d%Y")
filenamearr = []
mongousername = 'XXX'
mongopassword = 'XXXX'
client = MongoClient("mongodb+srv://%s:%s#XXXXX.XXXX.mongodb.net/?retryWrites=true&w=majority"%(mongousername,mongopassword))
db = client.DB1
logg = []
async def runbrowser(playwright,url):
async def handle_response(response,buttonnumber):
l = str(response.url)
para = 'param'
if para in l:
print(response.url)
textdata = await response.text()
subtask = asyncio.create_task(jsonparse(textdata))
done, pending = await asyncio.wait({subtask})
if subtask in done:
print("Success in Json parser")
result = await subtask
status = [buttonnumber,result]
logg.append(status)
print(status)
logdf = pd.DataFrame(logg)
logdf.columns = ['BUTTON','RESULT']
fname = 'XXXX' + today +".csv"
logdf.to_csv(fname,index=False)
async def jsonparse(textdata):
try:
#parsing happens here to output to MongoDB
return "Success"
except Exception as e:
print("Failled parsing")
return e
browser = await playwright.firefox.launch(
headless=True,
)
context = await browser.new_context(
locale='en-US',
ignore_https_errors = True,
)
page = await context.new_page()
await page.goto(url,timeout=0)
button = page.locator("xpath=//button[#event-list-item='']")
bcount = button.locator(":scope",has_text="Locator")
count = await bcount.count()
print(count)
for i in range(count):
print("\n\n\n\n\nSleeping 10 seconds before clicking button")
buttonnumber = i
await asyncio.sleep(10)
print("Clickking Button: ", i)
cbtn = bcount.nth(i)
await cbtn.hover()
await asyncio.sleep(4)
await cbtn.click()
if i==0:
print("i=0")
await page.reload(timeout=0)
retry = page.on("response",lambda response: handle_response(response,buttonnumber))
title = await page.title()
print(title)
print("Heading back to the main page.")
await page.go_back(timeout=0)
await page.reload()
await page.wait_for_timeout(5000)
await page.close()
print("Closing Tab")
await browser.close()
async def main():
tasks = []
async with async_playwright() as playwright:
url = 'https://samplelink.com'
tasks.append(asyncio.create_task(runbrowser(playwright,url)))
for t in asyncio.as_completed(tasks):
print(await t)
await asyncio.gather(*tasks)
asyncio.run(main())
After the start of the bans of accounts connected to my project, I changed the system for receiving new messages in the telegram account. Previously, I implemented it through a handler, now it is possible to connect several accounts, performing actions with unread messages on each one in turn. Code:
async def start_wtf_blyat():
global client, current_session_account
while True:
for cl in clients:
current_session_account = cl[0]
client = cl[1]
print(f'Choosing {current_session_account.session_name}')
if current_session_account.start_time is not None:
if current_session_account.start_time > dt.datetime.utcnow():
print(
f"{current_session_account.session_name}: {current_session_account.start_time.strftime('%d.%m.%Y %H:%M:%S')} > {dt.datetime.utcnow().strftime('%d.%m.%Y %H:%M:%S')}")
s_d = (current_session_account.start_time - dt.datetime.utcnow().replace(
microsecond=0)) * random.randrange(
1, 3)
print(f'{current_session_account.session_name} needs to sleep {s_d.seconds} seconds')
await asyncio.sleep(s_d.seconds)
print(f'{current_session_account.session_name}: Sleep complete!')
current_session_account.start_time = dt.datetime.utcnow().replace(microsecond=0)
current_session_account.activate()
async with client:
print(f'Starting {current_session_account.session_name}')
await check_news()
print(
f'{current_session_account.session_name}: Work complete! END: {current_session_account.end_time.strftime("%d.%m.%Y %H:%M:%S")}')
Then the necessary messages are selected in the check_news():
async def check_news():
global current_session_account, ME
ME = await client.get_me()
await asyncio.sleep(random.randrange(1, 5, 1))
# try:
x = [[d.unread_count, d.entity.id, d.title] for d in await client.get_dialogs() if
not getattr(d.entity, 'is_private', False) and type(d.entity) == Channel
and d.unread_count != 0 and d.entity.id in INPUT_CHANNELS_IDS]
if not x:
rnd_sleep = random.randrange(180, 300)
print(f'{current_session_account.session_name}: No channels, sleep for {rnd_sleep} seconds')
end_time = dt.datetime.utcnow().replace(microsecond=0)
start_time = current_session_account.start_time
if start_time is not None:
if start_time < end_time:
delta = end_time - start_time + dt.timedelta(seconds=rnd_sleep)
else:
delta = dt.timedelta(seconds=rnd_sleep)
print(f'{current_session_account.session_name} START: {start_time.strftime("%d.%m.%Y %H:%M:%S")}, '
f'END: {end_time.strftime("%d.%m.%Y %H:%M:%S")}, '
f'DELTA: {delta}, '
f'NEXT START {(end_time + delta).strftime("%d.%m.%Y %H:%M:%S")}')
current_session_account.set_times(delta)
current_session_account.deactivate()
return
for da in x:
print(f'{current_session_account.session_name}: {x.index(da) + 1} of {len(x)}')
await asyncio.sleep(random.randrange(1, 5, 1))
async for msg in client.iter_messages(da[1], limit=da[0]):
await asyncio.sleep(random.randrange(3, 5, 1))
await msg.mark_read()
if msg.text is None:
continue
comm_result_true = await Magic.detect_commercial(msg.text)
antiplagiat_result = await antiplagiat(msg)
if not comm_result_true and antiplagiat_result:
await send_this_post(msg, da[1])
else:
print(f'{current_session_account.session_name}: Commercial or plagiat!')
# finally:
end_time = dt.datetime.utcnow().replace(microsecond=0)
start_time = current_session_account.start_time
if start_time is not None:
if start_time < end_time:
delta = end_time - start_time + dt.timedelta(seconds=1)
else:
delta = dt.timedelta(seconds=2)
print(f'{current_session_account.session_name} START: {start_time.strftime("%d.%m.%Y %H:%M:%S")}, '
f'END: {end_time.strftime("%d.%m.%Y %H:%M:%S")}, '
f'DELTA: {delta}, '
f'NEXT START {(end_time + delta).strftime("%d.%m.%Y %H:%M:%S")}')
current_session_account.set_times(delta)
current_session_account.deactivate()
return
Finally, the message is processed, the media is downloaded, if any, the text is saved. And other actions are no longer related to the telegram api.
async def send_this_post(msg, result):
chan = db.get_input_channel(result)
if db.using_ai(chan[1]):
check = await Magic.detect_theme(msg.text)
if check:
msg_category = CAT_DEF[f'{check}']
else:
return
else:
msg_category = db.get_category_by_input_channel_name(chan[1])
print(f'Theme - {msg_category}')
test = await MSG(msg_cat=msg_category, txt=msg.text, title=chan[2], username=chan[1], datetime=msg.date)
await test.create_media(msg)
await test.create_voice()
await test.create_translates()
await send_to_users_test(test)
return
Everything starts as follows:
if __name__ == '__main__':
logging.warning('IZVESTNIK STARTED.')
loop = asyncio.get_event_loop()
bot.start(bot_token=settings.bot_TOKEN)
logging.warning(f'BOT {settings.bot_username} just launched.')
loop.create_task(usr_periods_activity())
loop.create_task(usr_msg_queue_activity())
loop.create_task(start_wtf_blyat())
bot.loop.run_forever()
In fact, all that each account does is receive unread messages, download media, mark them as read, but even the launch of 8 accounts resulted in the ban of each of them for 3 days, either in general without an error, or with an Account deactivated/deleted error (Caused get_dialogs request).
Although many users of the telegram application do many times more actions. Recently rereading the documentation, I came across this:
Text from documentation.
Perhaps the reason is that I am from Russia, and I use Russian SIM cards to register accounts, but a friend from England bought SIM cards for me there several times, but they also received a ban. The project release is located on the WDM server, the ip is also Russian, maybe that's the problem?
I also recommend to use different version
pip install Telethon==1.1
this version can't ban your account
The solution of this issue is just write an "impulse" activity script against pooling script. Also use SIM cards from another country for telegram accounts and proxy.
Im trying to write a discord bot that plays music. I am trying to convert spotify to youtube, but when I input large spotify playlists, it takes too long to queue all the songs. I want the spotify to youtube function run at the same time.
async def spottoyt(i):
trackid = response['items'][i]['track']['id']
track = sp.track(trackid)
trackname = track['name']
search = track['name'] + " " + track['artists'][0]['name']
result = await self.search_song(1, search, get_url=True)
if result is None:
await ctx.send(f":x: **No Matches for** ``{trackname}``")
else:
self.spotlist[ctx.guild.id].append(result[0])
for i in range(len(response['items'])):
t = threading.Thread(target=spottoyt, args=(i))
t.start()
t.join()
Running this gives me this error: TypeError: music.Player.play..spottoyt() argument after * must be an iterable, not int
On Discord, you can only have messages of character length 2000 or under. I am trying to append the server name, member amount and server ID for each server that the bot is in to a list, and then sending the list to a channel.
However, as the list length exceeds 2000 I have tried to split it up, however the method requires it to be updated every time manually as the list gets larger. How can I make the script automatically split up the list based on how many 'splits' are required and then send those 'splits'?
What I have so far, which works, but is not automatic:
#commands.command()
async def getallservers(self, ctx):
serverslist = []
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
if ctx.author.id == 204616460797083648:
for x in self.bot.guilds:
serverslist.append(f'{x.name}: **{len(x.members)}** - {x.id}\n')
q1,q2,q3,q4,q5,q6 = split_list(serverslist, wanted_parts=6)
embed = discord.Embed(title='Server List')
embed.description = ''.join(q1)
await ctx.send(embed=embed)
embed.description = ''.join(q2)
await ctx.send(embed=embed)
embed.description = ''.join(q3)
await ctx.send(embed=embed)
embed.description = ''.join(q4)
await ctx.send(embed=embed)
embed.description = ''.join(q5)
await ctx.send(embed=embed)
embed.description = ''.join(q6)
await ctx.send(embed=embed)
else:
pass
One you have the serverslist, you can pass it to a function that builds < 2000 character pages
def paginate(lines, chars=2000):
size = 0
message = []
for line in lines:
if len(line) + size > chars:
yield message
message = []
size = 0
message.append(line)
size += len(line)
yield message
then in your command
for message in paginate(serverlist):
embed.description = ''.join(message)
await ctx.send(embed=embed)