Recherche avancée

Médias (0)

Mot : - Tags -/flash

Aucun média correspondant à vos critères n’est disponible sur le site.

Autres articles (47)

  • Use, discuss, criticize

    13 avril 2011, par

    Talk to people directly involved in MediaSPIP’s development, or to people around you who could use MediaSPIP to share, enhance or develop their creative projects.
    The bigger the community, the more MediaSPIP’s potential will be explored and the faster the software will evolve.
    A discussion list is available for all exchanges between users.

  • MediaSPIP Player : problèmes potentiels

    22 février 2011, par

    Le lecteur ne fonctionne pas sur Internet Explorer
    Sur Internet Explorer (8 et 7 au moins), le plugin utilise le lecteur Flash flowplayer pour lire vidéos et son. Si le lecteur ne semble pas fonctionner, cela peut venir de la configuration du mod_deflate d’Apache.
    Si dans la configuration de ce module Apache vous avez une ligne qui ressemble à la suivante, essayez de la supprimer ou de la commenter pour voir si le lecteur fonctionne correctement : /** * GeSHi (C) 2004 - 2007 Nigel McNie, (...)

  • MediaSPIP Player : les contrôles

    26 mai 2010, par

    Les contrôles à la souris du lecteur
    En plus des actions au click sur les boutons visibles de l’interface du lecteur, il est également possible d’effectuer d’autres actions grâce à la souris : Click : en cliquant sur la vidéo ou sur le logo du son, celui ci se mettra en lecture ou en pause en fonction de son état actuel ; Molette (roulement) : en plaçant la souris sur l’espace utilisé par le média (hover), la molette de la souris n’exerce plus l’effet habituel de scroll de la page, mais diminue ou (...)

Sur d’autres sites (7421)

  • A Complete Guide to Metrics in Google Analytics

    11 janvier 2024, par Erin

    There’s no denying that Google Analytics is the most popular web analytics solution today. Many marketers choose it to understand user behaviour. But when it offers so many different types of metrics, it can be overwhelming to choose which ones to focus on. In this article, we’ll dive into how metrics work in Google Analytics 4 and how to decide which metrics may be most useful to you, depending on your analytics needs.

    However, there are alternative web analytics solutions that can provide more accurate data and supplement GA’s existing features. Keep reading to learn how to overcome Google Analytics limitations so you can get the more out of your web analytics.

    What is a metric in Google Analytics ?

    In Google Analytics, a metric is a quantitative measurement or numerical data that provides insights into specific aspects of user behaviour. Metrics represent the counts or sums of user interactions, events or other data points. You can use GA metrics to better understand how people engage with a website or mobile app. 

    Unlike the previous Universal Analytics (the previous version of GA), GA4 is event-centric and has automated and simplified the event tracking process. Compared to Universal Analytics, GA4 is more user-centric and lets you hone in on individual user journeys. Some examples of common key metrics in GA4 are : 

    • Sessions : A group of user interactions on your website that occur within a specific time period. A session concludes when there is no user activity for 30 minutes.
    • Total Users : The cumulative count of individuals who accessed your site within a specified date range.
    • Engagement Rate : The percentage of visits to your website or app that included engagement (e.g., one more pageview, one or more conversion, etc.), determined by dividing engaged sessions by sessions.
    Main overview dashboard in GA4 displaying metrics

    Metrics are invaluable when it comes to website and conversion optimisation. Whether you’re on the marketing team, creating content or designing web pages, understanding how your users interact with your digital platforms is essential.

    GA4 metrics vs. dimensions

    GA4 uses metrics to discuss quantitative measurements and dimensions as qualitative descriptors that provide additional context to metrics. To make things crystal clear, here are some examples of how metrics and dimensions are used together : 

    • “Session duration” = metric, “device type” = dimension 
      • In this situation, the dimension can segment the data by device type so you can optimise the user experience for different devices.
    • “Bounce rate” = metric, “traffic source/medium” = dimension 
      • Here, the dimension helps you segment by traffic source to understand how different acquisition channels are performing. 
    • “Conversion rate” = metric, “Landing page” = dimension 
      • When the conversion rate data is segmented by landing page, you can better see the most effective landing pages. 

    You can get into the nitty gritty of granular analysis by combining metrics and dimensions to better understand specific user interactions.

    How do Google Analytics metrics work ?

    Before diving into the most important metrics you should track, let’s review how metrics in GA4 work. 

    GA4 overview dashboard of engagement metrics
    1. Tracking code implementation

    The process begins with implementing Google Analytics 4 tracking code into the HTML of web pages. This tracking code is JavaScript added to each website page — it collects data related to user interactions, events and other important tidbits.

    1. Data collection

    As users interact with the website or app, the Google Analytics 4 tracking code captures various data points (i.e., page views, clicks, form submissions, custom events, etc.). This raw data is compiled and sent to Google Analytics servers for processing.

    1. Data processing algorithms

    When the data reaches Google Analytics servers, data processing algorithms come into play. These algorithms analyse the incoming raw data to identify the dataset’s trends, relationships and patterns. This part of the process involves cleaning and organising the data.

    1. Segmentation and customisation

    As discussed in the previous section, Google Analytics 4 allows for segmentation and customisation of data with dimensions. To analyse specific data groups, you can define segments based on various dimensions (e.g., traffic source, device type). Custom events and user properties can also be defined to tailor the tracking to the unique needs of your website or app.

    1. Report generation

    Google Analytics 4 can make comprehensive reports and dashboards based on the processed and segmented data. These reports, often in the form of graphs and charts, help identify patterns and trends in the data.

    What are the most important Google Analytics metrics to track ? 

    In this section, we’ll identify and define key metrics for marketing teams to track in Google Analytics 4. 

    1. Pageviews are the total number of times a specific page or screen on your website or app is viewed by visitors. Pageviews are calculated each time a web page is loaded or reloaded in a browser. You can use this metric to measure the popularity of certain content on your website and what users are interested in. 
    2. Event tracking monitors user interactions with content on a website or app (i.e., clicks, downloads, video views, etc.). Event tracking provides detailed insights into user engagement so you can better understand how users interact with dynamic content. 
    3. Retention rate can be analysed with a pre-made overview report that Google Analytics 4 provides. This user metric measures the percentage of visitors who return to your website or app after their first visit within a specific time period. Retention rate = (users with subsequent visits / total users in the initial cohort) x 100. Use this information to understand how relevant or effective your content, user experience and marketing efforts are in retaining visitors. You probably have more loyal/returning buyers if you have a high retention rate. 
    4. Average session duration calculates the average time users spend on your website or app per session. Average session duration = total duration of all sessions / # of sessions. A high average session duration indicates how interested and engaged users are with your content. 
    5. Site searches and search queries on your website are automatically tracked by Google Analytics 4. These metrics include search terms, number of searches and user engagement post-search. You can use site search metrics to better understand user intent and refine content based on users’ searches. 
    6. Entrance and exit pages show where users first enter and leave your site. This metric is calculated by the percentage of sessions that start or end on a specific page. Knowing where users are entering and leaving your site can help identify places for content optimisation. 
    7. Device and browser info includes data about which devices and browsers websites or apps visitors use. This is another metric that Google Analytics 4 automatically collects and categorises during user sessions. You can use this data to improve the user experience on relevant devices and browsers. 
    8. Bounce rate is the percentage of single-page sessions where users leave your site or app without interacting further. Bounce rate = (# of single-page sessions / total # of sessions) x 100. Bounce rate is useful for determining how effective your landing pages are — pages with high bounce rates can be tweaked and optimised to enhance user engagement.

    Examples of how Matomo can elevate your web analytics

    Although Google Analytics is a powerful tool for understanding user behaviour, it also has privacy concerns, limitations and a list of issues. Another web analytics solution like Matomo can help fill those gaps so you can get the most out of your analytics.

    Examples of how Matomo and GA4 can elevate each other
    1. Cross-verify and validate your observations from Google Analytics by comparing data from Matomo’s Heatmaps and Session Recordings for the same pages. This process grants you access to these advanced features that GA4 does not offer.
    Matomo's heatmaps feature
    1. Matomo provides you with greater accuracy thanks to its privacy-friendly design. Unlike GA4, Matomo can be configured to operate without cookies. This means increased accuracy without intrusive cookie consent screens interrupting the user experience. It’s a win for you and for your users. Matomo also doesn’t apply data sampling so you can rest assured that the data you see is 100% accurate.
    1. Unlike GA4, Matomo offers direct access to customer support so you can save time sifting through community forum threads and online documentation. Gain personalised assistance and guidance for your analytics questions, and resolve issues efficiently.
    Screenshot of the Form Analytics Dashboard, showing data and insights on form usage and performance
    1. Matomo’s Form Analytics and Media Analytics extend your analytics capabilities beyond just pageviews and event tracking.

      Tracking user interactions with forms can tell you which fields users struggle with, common drop-off points, in addition to which parts of the form successfully guide visitors towards submission.

      See first-hand how Concrete CMS 3x their leads using Matomo’s Form Analytics.

      Media Analytics can provide insight into how users interact with image, video, or audio content on your website. You can use this feature to assess the relevance and popularity of specific content by knowing what your audience is engaged by.

    Try Matomo for Free

    Get the web insights you need, without compromising data accuracy.

    No credit card required

    Final thoughts

    Although Google Analytics is a powerful tool on its own, Matomo can elevate your web analytics by offering advanced features, data accuracy and a privacy-friendly design. Don’t play a guessing game with your data — Matomo provides 100% accurate data so you don’t have to rely on AI or machine learning to fill in the gaps. Matomo can be configured cookieless which also provides you with more accurate data and a better user experience. 

    Lastly, Matomo is fully compliant with some of the world’s strictest privacy regulations like GPDR. You won’t have to sacrifice compliance for accurate, high quality data. 

    Start your 21-day free trial of Matomo — no credit card required.

  • Conversion Funnel Optimisation : 10 Ways to Convert More

    24 janvier 2024, par Erin

    Converting leads into happy customers is the ultimate goal of any sales and marketing team. But there are many steps in between those two events, or in other words, funnel stages. 

    Your sales funnel includes all the steps you take to make your audience aware of your product or services and convince them to purchase. Conversion funnel optimisation strategies can help you move users through the stages of your sales funnel. 

    This article will show you how to optimise your conversion funnel and boost sales — no matter how your funnel looks. We’ll go over practical tips you can implement and how you can analyse and measure results.

    Let’s get started.

    What is conversion funnel optimisation ? 

    Conversion funnel optimisation is the strategic and ongoing process of refining and improving the different stages of a sales or marketing funnel to increase the rate at which users complete desired actions.

    A sales funnel represents the stages a potential customer goes through before purchasing. 

    The typical stages of a sales funnel include :

    • Awareness : At the top of the funnel, potential customers become aware of your product or service. 
    • Consideration : In this stage, prospects evaluate the product or service against alternatives. They may compare features, prices and customer reviews to make an informed decision.
    • Conversion : The prospect completes the transaction and becomes an actual customer by purchasing.
    • Loyalty : You can turn one-time buyers into repeat customers and brand advocates. 

    It’s called a “funnel” because, similar to the shape of a funnel, the number of potential customers decreases as they progress through the various stages of the sales process — as you can see illustrated below.

    Marketing funnel stages

    Sales funnels can vary across industries and business models, but the general concept remains the same. The goal is to guide potential customers through each funnel stage, addressing their needs and concerns at each step, ultimately leading to a successful conversion. 

    You can create and monitor a custom funnel for your site’s user journey with a web analytics solution like Matomo.

    Try Matomo for Free

    Get the web insights you need, without compromising data accuracy.

    No credit card required

    The importance of conversion funnel optimisation 

    At the heart of conversion funnel optimisation is the quest for higher conversion rates

    Refining the customer journey can increase the chances of turning visitors into customers who return repeatedly.

    Specifically, here’s how conversion funnel optimisation can benefit your business :

    • Increased conversions : Marketers can increase the likelihood of turning website visitors into customers by making the user journey more user-friendly and persuasive.
    • Higher revenue : Improved conversion rates aren’t just numbers on a chart ; they translate to tangible revenue. 
    • Increased ROI (return on investment) : By optimising the conversion funnel, you can get more value from your marketing and sales efforts. 
    • Improved customer satisfaction : When customers find it easy and enjoyable to interact with a website or service, it positively influences their satisfaction and likelihood of returning.
    • Data-driven decision-making : Businesses can make informed decisions on budgets and resources based on user behaviour and performance metrics by analysing and optimising conversion funnels.

    ​​Ultimately, conversion funnel optimisation efforts align the entire funnel with overarching business goals.

    10 ways to optimise your conversion funnel 

    Here are 10 ways to optimise your conversion funnel.

    1. Identify and segment your target audience

    The key to a successful conversion funnel begins with a deep understanding of your target audience. 

    Identifying and segmenting your audience lets you speak directly to their pain points, desires and motivations.

    One effective way to know your audience better is by creating detailed buyer personas. These are fictional representations of your ideal customers based on thorough market research and real data. Dive into demographics and behavioural patterns to craft personas that resonate with your audience.

    Audience segmentation

    Note that consumer preferences are not static. They evolve, influenced by trends, technological advancements and shifts in societal values. Staying attuned to these changes is crucial as part of optimising your conversion funnel.

    Thus, you must regularly update your buyer personas and adjust your marketing strategies accordingly.

    2. Create content for every stage of the funnel

    Each funnel stage represents a different mindset and needs for your potential customers. Tailoring your content ensures you deliver the right message at the right time to the right audience. 

    Here’s how to tailor your content to fit prospective customers at every conversion funnel stage.

    Awareness-stage content

    Prospects here are seeking information. Your content should be educational and focused on addressing their pain points. Create blog posts, infographics and videos introducing them to your industry, product or service.

    This video we created at Matomo is a prime example of awareness-stage content, grabbing attention and educating viewers about Matomo.

    Consideration-stage content

    Prospects are evaluating their options. Provide content highlighting your product’s unique selling points, such as case studies, product demonstrations and customer testimonials.

    Here’s how we use a versus landing page at Matomo to persuade prospects at this funnel stage.

    Versus page example from Matomo comparing Google Analytics alternative

    Conversion-stage content

    This is the final push. Ensure a smooth transition to conversion with content like promotional offers, limited-time discounts and clear calls to action (CTA).

    Loyalty-stage content

    In this stage, you might express gratitude for the purchase through personalised thank-you emails. Follow up with additional resources, tips or exclusive offers to reinforce a positive post-purchase experience. This also positions your brand as a helpful resource beyond the initial sale.

    Reward customer loyalty with exclusive offers, discounts or membership in a loyalty program.

    3. Capture leads

    Lead magnets are incentives offered to potential customers in exchange for their contact information, typically their email addresses. 

    Examples of lead magnets include :

    • Ebooks and whitepapers : In-depth resources that delve into specific topics of interest to your target audience.
    • Webinars and workshops : Live or recorded sessions that offer valuable insights, training or demonstrations.
    • Free trials and demos : Opportunities for potential customers to experience your product or service firsthand.
    • Checklists and templates : Practical tools that help your audience solve specific challenges.
    • Exclusive offers and discounts : Special promotions are available to those who subscribe or provide their contact information.

    For instance, here’s how HubSpot uses templates as lead magnets.

    HubSpot templates

    Similarly, you can incorporate your lead magnets into relevant articles or social media posts, email campaigns and other marketing channels.

    4. Optimise your landing pages

    Understanding how visitors interact with your landing pages is a game-changer. So, the first step in optimising your landing pages is to analyse them.

    Enter Matomo’s heatmaps — the secret weapon in landing page optimisation. They visually represent how users interact with your pages, revealing where they linger, what catches their attention and where they may encounter friction. 

    Matomo Heatmaps Feature

    Here are a few landing page elements you should pay attention to :

    • Strategic visual elements : Integrate high-quality images, videos and graphics that support your message and guide visitors through the content.
    • Compelling copy : Develop concise and persuasive copy that emphasises the benefits of your offering, addressing user pain points.
    • Effective CTA : Ensure your CTA is prominently displayed, using compelling language and colours that stand out.
    • Mobile responsiveness : Optimise your landing pages for various devices, especially considering the prevalence of mobile users.
    • Minimal form fields : Reduce friction by keeping form fields to a minimum, requesting only essential information.
    • ​​Leverage social proof : Integrate testimonials, reviews and trust badges to build trust and credibility.
    • A/B testing : Experiment with variations in design, copy and CTAs through A/B testing, allowing data to guide your decisions.

    Try Matomo for Free

    Get the web insights you need, without compromising data accuracy.

    No credit card required

    5. ​​Use compelling Calls to Action (CTAs)

    Crafting compelling CTAs is an art that involves a careful balance of persuasion, clarity and relevance.

    Here are a few tips you can implement to write CTAs that support your goals :

    • Use language that compels action. Instead of generic phrases like “Click Here,” opt for more persuasive alternatives such as “Unlock Exclusive Access” or “Start Your Free Trial.”
    • Make sure your CTAs are clear and straightforward. Visitors should instantly understand what action you want them to take. 
    • Tailor CTAs to the specific content on the page. Whether it’s a blog post, landing page or email, the CTA should seamlessly connect with the surrounding context.
    • Position your CTAs strategically. They should be prominently displayed and easily noticeable, guiding visitors without intruding.
    • Create a sense of urgency. Encourage immediate action by incorporating language that instils a sense of urgency. Phrases like “Limited Time Offer” or “Act Now” can prompt quicker responses.

    6. Have an active social presence

    Social media platforms are bustling hubs of activity where your target audience spends a significant portion of their online time. Cultivating a social media presence allows you to meet your audience where they are, fostering a direct line of communication.

    Moreover, the integration of shopping features directly into social media platforms transforms them into seamless shopping experiences. Nearly half of Instagram users shop weekly through the platform. 

    Also, the US social commerce sales continue to grow each year and are expected to reach $79.64 billion by 2025.

    Graph showing the UD social commerce sales 2019-2025

    7. Build a brand community

    Four in five customers consider communities important to how engaged they are with a brand.

    A strong community fosters a sense of belonging and loyalty among members. When customers feel connected to your brand and each other, they are more likely to remain loyal over the long term. 

    Also, satisfied community members often share their positive experiences with others, expanding your brand’s reach without additional marketing efforts.

    For example, Nike’s community for runners is a digital space where individuals share their running journeys, accomplishments and challenges. 

    Nike Run Club page

    By strategically building and nurturing a community, you not only enhance retention and spur referrals but also create a space where your brand becomes an integral part of your customers’ lives. 

    8. Conduct A/B tests

    A/B testing systematically compares two versions of a webpage, email or other content to determine which performs better.

    Examples of elements to A/B test :

    • CTAs : The language, colour, size and placement of CTAs can significantly impact user engagement. A/B testing allows you to discover which variations prompt the desired actions.
    • Headlines : Crafting compelling headlines is an art. Test different versions to identify which headlines resonate best with your audience, whether they are more drawn to clarity, humour, urgency or curiosity.
    • Images : Test different images to understand your audience’s visual preferences. This could include product images, lifestyle shots or graphics.
    Matomo A/B Test feature

    With Matomo’s A/B testing feature, you can test various elements to see which is successful in converting visitors or moving them to the next stage of the conversion funnel.

    9. Leverage social proof

    In an era where consumers are inundated with choices, the opinions, reviews and endorsements of others serve as beacons, guiding potential customers through the decision-making process. 

    Simply put — when people see that others have had positive experiences with your brand, it instils trust and confidence.

    Importance of social proof

    You can proactively gather social proof and display it prominently across your marketing channels. Here are some examples of social proof you can leverage :

    • Customer reviews : Positive reviews and testimonials from satisfied customers serve as authentic endorsements of your products or services. 
    • Case studies : In-depth case studies that showcase successful collaborations or solutions provided to clients offer a detailed narrative of your brand’s capabilities. These are particularly effective in B2B scenarios or for complex products and services.
    • User-generated content : Encourage customers to share their experiences. This could include photos, videos or posts on social media platforms, providing a dynamic and genuine portrayal of your brand.
    • Influencer endorsements : Collaborating with influencers in your industry or niche can amplify your social proof. When influencers vouch for your products or services, their followers are more likely to take notice.

    10. Measure and analyse performance

    This is a continuous loop of refinement, where you should use analysis and data-driven insights to guide your conversion funnel optimisation efforts.

    Here’s a systematic approach you can take :

    1. Identify the path users take on your site using a feature like Users Flow.
    2. Map the customer journey using a Funnels feature like the one in Matomo. 
    3. Identify the metrics that align with your conversion goals at each stage of the funnel, such as website traffic, conversion rates, click-through rates and customer acquisition costs.
    4. Assess conversion rates at different stages of the funnel. Identify areas with significant drop-offs and investigate factors that might contribute to the decline.
    5. Use heatmaps and session recordings to see first-hand how users interact with your site.
    6. Create an experiment to test and improve a specific area within your funnel using insights from the heatmaps and session recordings.
    7. A/B test, analyse the results to understand which variations performed better. Use this data to refine elements within your funnel.

    See how Concrete CMS 3x their leads with conversion optimisation.

    Conclusion 

    The customer journey is not linear. However, it involves a few specific stages your audience will go through — from first learning about your product or services to considering whether to try it. The goal is to turn them into happy and loyal customers.

    In this article, we went over strategies and practical tips you can use to guide customers through the conversion funnel. From segmenting your audience to capturing leads, optimising landing pages and running A/B tests, there are steps you can take to ensure your audience will move to the next stage.

    And of course, you have to continuously measure and analyse your performance. That’s how you know whether you’re heading in the right direction and, if not, where to correct your course. 

    For that, you need a robust web analytics solution with conversion optimisation features. Try Matomo free for 21 days and start optimising your conversion funnel—no credit card required. 

  • "FFmpeg : Error not transitioning to the next song in Discord Bot's queue."

    1er avril 2024, par noober

    I have 3 modules, but I'm sure the error occurs within this module, and here is the entire code within that module :

    


    import asyncio
import discord
from discord import FFmpegOpusAudio, Embed
import os

async def handle_help(message):
    embed = discord.Embed(
        title="Danh sách lệnh cho Bé Mèo",
        description="Dưới đây là các lệnh mà chủ nhân có thể bắt Bé Mèo phục vụ:",
        color=discord.Color.blue()
    )
    embed.add_field(name="!play", value="Phát một bài hát từ YouTube.", inline=False)
    embed.add_field(name="!pause", value="Tạm dừng bài hát đang phát.", inline=False)
    embed.add_field(name="!resume", value="Tiếp tục bài hát đang bị tạm dừng.", inline=False)
    embed.add_field(name="!skip", value="Chuyển đến bài hát tiếp theo trong danh sách chờ.", inline=False)
    embed.add_field(name="!stop", value="Dừng phát nhạc và cho phép Bé Mèo đi ngủ tiếp.", inline=False)
    # Thêm các lệnh khác theo cùng mẫu trên
    await message.channel.send(embed=embed)

class Song:
    def __init__(self, title, player):
        self.title = title  # Lưu trữ tiêu đề bài hát ở đây
        self.player = player

# Thêm đối tượng Song vào hàng đợi
def add_song_to_queue(guild_id, queues, song):
    queues.setdefault(guild_id, []).append(song)

async def handle_list(message, queues):
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    if os.path.exists(log_file_path):
        with open(log_file_path, "r", encoding="utf-8") as f:
            song_list = f.readlines()

        if song_list:
            embed = discord.Embed(
                title="Danh sách bài hát",
                description="Danh sách các bài hát đã phát:",
                color=discord.Color.blue()
            )

            for i, song in enumerate(song_list, start=1):
                if i == 1:
                    song = "- Đang phát: " + song.strip()
                embed.add_field(name=f"Bài hát {i}", value=song, inline=False)

            await message.channel.send(embed=embed)
        else:
            await message.channel.send("Hiện không có dữ liệu trong file log.")
    else:
        await message.channel.send("File log không tồn tại.")

async def handle_commands(message, client, queues, voice_clients, yt_dl_options, ytdl, ffmpeg_options=None, guild_id=None, data=None):
    # Nếu không có ffmpeg_options, sử dụng các thiết lập mặc định
    if ffmpeg_options is None:
        ffmpeg_options = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': '-vn -filter:a "volume=0.25"'
        }
    
    # Khởi tạo voice_client
    if guild_id is None:
        guild_id = message.guild.id

    if guild_id in voice_clients:
        voice_client = voice_clients[guild_id]
    else:
        voice_client = None

    # Xử lý lệnh !play
    if message.content.startswith("!play"):
        try:
            # Kiểm tra xem người gửi tin nhắn có đang ở trong kênh voice không
            voice_channel = message.author.voice.channel
            # Kiểm tra xem bot có đang ở trong kênh voice của guild không
            if voice_client and voice_client.is_connected():
                await voice_client.move_to(voice_channel)
            else:
                voice_client = await voice_channel.connect()
                voice_clients[guild_id] = voice_client
        except Exception as e:
            print(e)

        try:
            query = ' '.join(message.content.split()[1:])
            if query.startswith('http'):
                url = query
            else:
                query = 'ytsearch:' + query
                loop = asyncio.get_event_loop()
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(query, download=False))
                if not data:
                    raise ValueError("Không có dữ liệu trả về từ YouTube.")
                url = data['entries'][0]['url']

            player = FFmpegOpusAudio(url, **ffmpeg_options)
            # Lấy thông tin của bài hát mới đang được yêu cầu
            title = data['entries'][0]['title']
            duration = data['entries'][0]['duration']
            creator = data['entries'][0]['creator'] if 'creator' in data['entries'][0] else "Unknown"
            requester = message.author.nick if message.author.nick else message.author.name
                    
            # Tạo embed để thông báo thông tin bài hát mới
            embed = discord.Embed(
                title="Thông tin bài hát mới",
                description=f"**Bài hát:** *{title}*\n**Thời lượng:** *{duration}*\n**Tác giả:** *{creator}*\n**Người yêu cầu:** *{requester}*",
                color=discord.Color.green()
            )
            await message.channel.send(embed=embed)
            
            # Sau khi lấy thông tin của bài hát diễn ra, gọi hàm log_song_title với title của bài hát
            # Ví dụ:
            title = data['entries'][0]['title']
            await log_song_title(title)

            # Thêm vào danh sách chờ nếu có bài hát đang phát
            if voice_client.is_playing():
                queues.setdefault(guild_id, []).append(player)
            else:
                voice_client.play(player)
                
        except Exception as e:
            print(e)
            
    if message.content.startswith("!link"):
            try:
                voice_client = await message.author.voice.channel.connect()
                voice_clients[voice_client.guild.id] = voice_client
            except Exception as e:
                print(e)

            try:
                url = message.content.split()[1]

                loop = asyncio.get_event_loop()
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

                song = data['url']
                player = discord.FFmpegOpusAudio(song, **ffmpeg_options)

                voice_clients[message.guild.id].play(player)
            except Exception as e:
                print(e)

    # Xử lý lệnh !queue
    elif message.content.startswith("!queue"):
        queue = queues.get(guild_id, [])
        if queue:
            await message.channel.send("Danh sách chờ:")
            for index, item in enumerate(queue, 1):
                await message.channel.send(f"{index}. {item.title}")
        else:
            await message.channel.send("Không có bài hát nào trong danh sách chờ.")

    # Xử lý lệnh !skip
    elif message.content.startswith("!skip"):
        try:
            if voice_client and voice_client.is_playing():
                voice_client.stop()
                await play_next_song(guild_id, queues, voice_client, skip=True)
                await remove_first_line_from_log()
        except Exception as e:
            print(e)

    # Xử lý các lệnh như !pause, !resume, !stop
    elif message.content.startswith("!pause"):
        try:
            if voice_client and voice_client.is_playing():
                voice_client.pause()
        except Exception as e:
            print(e)

    elif message.content.startswith("!resume"):
        try:
            if voice_client and not voice_client.is_playing():
                voice_client.resume()
        except Exception as e:
            print(e)

    elif message.content.startswith("!stop"):
        try:
            if voice_client:
                voice_client.stop()
                await voice_client.disconnect()
                del voice_clients[guild_id]  # Xóa voice_client sau khi dừng
        except Exception as e:
            print(e)

async def log_song_title(title):
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        # Kiểm tra xem tệp tin log đã tồn tại chưa
        if not os.path.exists(log_file_path):
            # Nếu chưa tồn tại, tạo tệp tin mới và ghi title vào tệp tin đó
            with open(log_file_path, 'w', encoding='utf-8') as file:
                file.write(title + '\n')
        else:
            # Nếu tệp tin log đã tồn tại, mở tệp tin và chèn title vào cuối tệp tin
            with open(log_file_path, 'a', encoding='utf-8') as file:
                file.write(title + '\n')
    except Exception as e:
        print(f"Error logging song title: {e}")

async def remove_first_line_from_log():
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        with open(log_file_path, "r", encoding="utf-8") as f:
            lines = f.readlines()
        # Xóa dòng đầu tiên trong list lines
        lines = lines[1:]
        with open(log_file_path, "w", encoding="utf-8") as f:
            for line in lines:
                f.write(line)
    except Exception as e:
        print(f"Error removing first line from log: {e}")
        
async def clear_log_file():
    log_file_path = "C:\\Bot Music 2\\song_log.txt"
    try:
        with open(log_file_path, "w", encoding="utf-8") as f:
            f.truncate(0)
    except Exception as e:
        print(f"Error clearing log file: {e}")


async def play_next_song(guild_id, queues, voice_client, skip=False):
    queue = queues.get(guild_id, [])
    if queue:
        player = queue.pop(0)
        voice_client.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next_song(guild_id, queues, voice_client, skip=False), voice_client.loop))
        if skip:
            return
        else:
            await remove_first_line_from_log()  # Xóa dòng đầu tiên trong file log
    elif skip:
        await remove_first_line_from_log()  # Xóa dòng đầu tiên trong file log
        await voice_client.disconnect()
        del voice_client[guild_id]  # Xóa voice_client sau khi dừng
    else:
        await clear_log_file()  # Xóa dòng đầu tiên trong file log
        await voice_client.disconnect()
        del voice_client[guild_id]  # Xóa voice_client sau khi dừng


    


    I have tried asking ChatGPT, Gemini, or Bing, and they always lead me into a loop of errors that cannot be resolved. This error only occurs when the song naturally finishes playing due to its duration. If the song is playing and I use the command !skip, the next song in the queue will play and function normally. I noticed that it seems like if a song ends naturally, the song queue is also cleared immediately. I hope someone can help me with this