Chrookie
Chrookie

Reputation: 23

Python Split string after 2000 characters

I'm working on a discord bot that can return the summary of Wikipedia articles. but there's an issue, some summaries are longer than 2000 characters, which exceeds discord's character limit. is there a way I can split my string into multiple messages?

The string I want to split is str(wikipedia.search(query)) (the entire thing is in an embed block):

embedVar = discord.Embed(title=str(query)
description=str(wikipedia.search(query)), color=0x9CAFBE)
await message.channel.send(embed=embedVar)

Upvotes: 2

Views: 1654

Answers (2)

Tyler
Tyler

Reputation: 142

To expand what Darina commented, splice the string before you post it on discord.

posted_string = str(wikipedia.search(query))[:2000]
embedVar = discord.Embed(title=str(query),
                         description=posted_string,
                         color=0x9CAFBE) await message.channel.send(embed=embedVar)

A 'string' is an array of characters. When you assign it to another variable by using [:2000], you're telling the interpreter to put all the characters from the beginning of the array up to, but not including, the 2000th character.

EDIT: As Ironkey mentions in the comments, hardcoding values isn't viable since we don't know exactly how many characters an article has. Try this untested code instead:

wiki_string = str(wikipedia.search(query))
string_length = len(wiki_string)
if string_len < 2000:
    embedVar = discord.Embed(title=str(query),
                         description=wiki_string,
                         color=0x9CAFBE)
    await message.channel.send(embed=embedVar)
else:
    max_index = 2000
    index = 0
    while index < (string_length - max_index): 
        posted_string = wiki_string[index:max_index]
        embedVar = discord.Embed(title=str(query),
                         description=posted_string,
                         color=0x9CAFBE)
        await message.channel.send(embed=embedVar)
        index = index + max_index
    posted_string = wiki_string[index-max_index:]
    embedVar = discord.Embed(title=str(query),
                         description=wiki_string,
                         color=0x9CAFBE)
    await message.channel.send(embed=embedVar)

If this doesn't work, please let me know where it failed. Thanks!

Upvotes: 2

Ironkey
Ironkey

Reputation: 2607

heres a solution:

article = "5j5rtOf8jMePXn7a350fOBKVHoAJ4A2sKqUERWxyc32..." # 4000 character string i used 
chunklength = 2000
chunks = [article[i:i+chunklength ] for i in range(0, len(article), chunklength )]

print(len(chunks))

output

2

an extension on how you could use it:

for chunk in chunks: 
    embedVar = discord.Embed(title="article name",
                         description=chunk ,
                         color=0x9CAFBE) 
await ctx.send(embed=embedVar)

Upvotes: 4

Related Questions