Getting more than 1 post from a sub at a time - discord

reddit = praw.Reddit(client_id='xyz',
client_secret='xyz',
user_agent='xyz',check_for_async=False)
#bot.command(aliases=['memes'])
async def meme(ctx):
memes_submissions = reddit.subreddit('dankmemes').new()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
embed = discord.Embed(title= f"Meme-" ,color=0xFF00FF)
embed.set_image(url=submission.url)
'''embed.set_thumbnail(url=ctx.author.avatar_url)'''
embed.set_footer(text='requested by: \n{0}'.format(ctx.author),icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
i wrote this down to extract 1 meme at a time from reddit sub "dankmemes"
i was wondering if theres a way through which i can ask for top 5 memes or get more than just one meme?
any suggestions will be of a lot of help. tysm!

You can get top posts from a subreddit by using the subreddit.top member.
max_top = 5
subreddit = reddit.subreddit('sample_subreddit_with_good_memes')
top = subreddit.top(limit=max_top)
The built-in random library has a function named choices() which gives you a list with multiple randomly selected choices. So you can basically get the top 100 posts and then get 10 random memes from the list.

Related

Discord.py user command counter

I am currently trying to implement a counter to show how many times a user has used a command like "*kiss #randomuser", and then it would show in the embed footer or under title "user has kissed someone {number} of times"
I have tried the solution found here How do I get a counter to work within a discord.py command function?
but nothing I have tried has worked, I apologize but im not every good with this
bot.counter = 0
#bot.command()
##commands.cooldown(1,10,commands.BucketType.user)
async def Random(ctx, member:discord.Member = None):
bot.counter += 1
if member == ctx.author:
em = discord.Embed(title=f'{ctx.author.display_name}, You can not perform this action on yourself ', color = random.randint(0, 16777215) )
await ctx.reply(embed=em)
else:
e = discord.Embed(title=f'{ctx.author.display_name} is doing something random to {member.name}', color = random.randint(0, 16777215))
content = []
link = random.choice(content)
e.set_image(url=f'{link}')
e.set_footer(text=f"This user has used this command {bot.counter}")
await ctx.reply(embed=e)
```

Use feeder next 10 results and repeat the request 10 times in Gatling

I am using Gatling 3.6.1 and I am trying to repeat the request 10 times for the next 10 products from the feeder file. This is what I tried:
feed(products, 10)
.repeat(10, "index") {
exec(session => {
val index = session("index").as[Int]
val counter = index + 1
session.set("counter", counter)
})
.exec(productIdsRequest())
}
private def productIdsRequest() = {
http("ProductId${counter}")
.get(path + "products/${product_code${counter}}")
.check(jsonPath("$..code").count.gt(2))
}
I am having trouble getting the counter value to my API URL.
I would like to have something like
products/${product_code1},
products/${product_code2} etc.
But instead, I get the error 'nested attribute definition is not allowed'
So basically I would like that every request gets called with one product from the feeder (in the batch of 10 products)
Can you please help?
Thanks!
Disclaimer: I don't know how realized your feeder products.
If I clearly understand you - just need to move .repeat on high level:
.repeat(10, "counter") {
feed(product)
.exec(http("ProductId ${counter}")
.get("products/${product_code}")
.check(jsonPath("$..code").count.gt(2)))
}

How to index into the channel.members list and take out the name? Closed

So I'm trying to get the names of all the people in a voice channel, but the bot returns a list like so:
[<Member id=704069756717629472 name='Eedward' discriminator='8402' bot=False nick=None guild=<Guild id=807690875802878003 name='lfg testing' shard_id=None chunked=True member_count=3>>]
Is there any way I can take that "name" part out of the list? Or is there a better way to do something like this? This is my code:
#client.command()
async def lfg(ctx, game, *,extra=None):
if not ctx.message.author.voice:
await ctx.send(f"{ctx.author.name}, you need to connect to a voice channel first to use this command.")
return
else:
channel = ctx.message.author.voice.channel
link = await channel.create_invite(max_age = 300)
members = len(ctx.message.author.voice.channel.members)
members1 = ctx.message.author.voice.channel.members
max_ = channel.user_limit
if max_ == 0:
max_ = 'None'
if max_ == 'None':
p = f'{members}, No Limit'
else:
p = f"{members} out of {max_}"
em = Embed(color=discord.Color.gold())
em.add_field(name='LFG Request', value=f"**{ctx.author.mention} is looking for a group in voice channel `#{channel}`**:\n\n**Game: {game}**\n\n**Extra Info:** {extra}\n\n**Connected Users:**{(members1)} ({p})\n\n**VC Invite: [Click here to join]({link})**")
em.set_footer(text=f'Type !lfg (message) to create this embed | This LFG request was made by {ctx.author.name}')
await ctx.send(embed=em)
Sorry if it's a bit hard to read, thanks in advance! :D (Btw I'm trying to display the names of the users in the vc in the "Connected Users" section of the embed)
Edit: I figured it out, for those who want the code, here it is:
members = len(ctx.message.author.voice.channel.members)
count = 0
members1 = ""
for _ in range(int(members)):
members1 += f"{ctx.message.author.voice.channel.members[count].mention}"
count += 1
try adding .name to the member. This should get the name from the member.

Loop function to fill Crosselling template

I need to create a file containing information on crosselling for my webshop.
In my example file you'll see the tab "Basic Data", this is the data available to me already. Column A contains certain products, column B shows the assigned (product)categories.
The Tab "Starting Point" shows how the final file will be structured and how the function should come into play. It would need to do the following:
Copy the first product from the Unique product list (D2) to A2 (already done here)
Paste a filterfunction into B2 (already done here)
This filterfunction lists all products that belong to the same category like Product 1 except for Product 1 itself
Apply a numerical position tag in tens in Column C to the whole range of products related to Product 1 (in this case B2:B4), starting from 10 (..20, 30, ff) and optimally randomize it. (already done here)
Drag down A2, respectively paste "Product 1" into all cells below A2 until the end of the result of the filterfunction in Columns B is reached (already done here).
Continue the loop by pasting "Product 2" into A5, pasting the filterfunction into B5 and so on.
In "Desired Result" you can see how the end result should look like in this example. There are only 8 products, but I'd need to be able to do this for hundreds of products, that's why a function is needed.
I hope somebody is able to help me here.
Answer
You can get your desired result using Google Apps Script as I suggested.
How to use it:
Open Apps Script clicking on Tools > Script editor and you will see the script editor. It is based on JavaScript and it allows you to create, access, and modify Google Sheets files with a service called Spreadsheet Service.
Paste the following code and click on Run
Code
function main() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetResult = ss.getSheetByName('Desired Result')
const sheetBasic = ss.getSheetByName('Basic Data')
// write unique products
const val = "=ARRAYFORMULA(UNIQUE('Basic Data'!A2:A))"
sheetResult.getRange('D2').setValue(val)
// get basic data
const lastColumn = sheetBasic.getRange('A:A').getValues().filter(String).length; // number of products
const cat = sheetBasic.getRange('A2:B'+lastColumn).getValues() // product | category
const productGroup = [] // array to store data
// loop each product
for (var j=0; j<cat.length; j++){
const p1 = cat[j]
var k = 1
for (var i=0; i<cat.length; i++){
if (cat[i][1] == p1[1] && cat[i][0] != p1[0]){
const val = [p1[0],cat[i][0],k*10]
k = k + 1
productGroup.push(val)
}
}
}
var n = productGroup.length+1
sheetResult.getRange('A2:C'+n).setValues(productGroup)
}
Some comments
This solution does not randomize the position value. If you need it I can help you with that, but first I want to check that this solution fits you.
Let me know if you can obtain your desired result. Keep in mind that this solution uses the name of the sheets.
Reference
Google Apps Script
Spreadsheet Service
JavaScript

How to get all friends - TweetSharp

I'm using the ListFriends() method of TweetSharp library to get all friends of my user (My user has 500 friends).
TwitterCursorList<TwitterUser> friendsList = service.ListFriends(new ListFriendsOptions { Cursor=-1,SkipStatus=true});
while (friendsList.NextCursor != null)
{
foreach (var item in friendsList)
{
count++;
}
TwitterCursorList<TwitterUser> friendsList = service.ListFriends(new ListFriendsOptions { Cursor = friendsList.NextCursor, SkipStatus = true });
}
The above code is working well but it gives me only 300 friends because ListFriends() method has rate limit of 15 per 15 mins and when I'm trying to get more friends its rate limits get over.
How to get all friends in one attempt coz my requirement is to show all friends.
friends/ids will give you the id's of your friends (5.000 max/request). After that you can do a users/show to get the details for the userid's. I don't know what TweetSharp methods you need to use, but I think you can find that in the documentation.
You have one mistake in your code. You cant define friendsList again inside your loop. Thus the last line of code should looks like:
friendsList = service.ListFriends(new ListFriendsOptions { Cursor = friendsList.NextCursor, SkipStatus = true });

Resources